[問題] Segmentation fault (core dumped)的問題
開發平台(Platform): (Ex: Win10, Linux, ...)
Linux centos7
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
無
問題(Question):
我利用getline把cin的整行文字或數字存成string,但想個別處理這個string的每一個
字,所以我另外用了一個vector<string>去逐字的塞進去。
用的方法是在for迴圈內加入:vector[i].push_back(string.at(i));
但編譯沒問題後,在我cin餵入資料後,卻顯示Segmentation fault (core dumped)。
餵入的資料(Input):
隨意字串
預期的正確結果(Expected Output):
個別塞入vector中運用
錯誤結果(Wrong Output):
Segmentation fault (core dumped)
程式碼(Code):(請善用置底文網頁, 記得排版)
1 #include <iostream>
2 #include <fstream>
3 #include <string>
4 #include <vector>
5 using namespace std;
6
7
8 int main()
9 {
10 vector<string> v;
11 string sin;
12
13 cout << "input"<<endl;
14 getline(cin,sin);
15
16 for(int i=0 ;i < sin.length() ; i++)
17 {
18 v[i].push_back(sin.at(i));
19 }
20 /*
21 for(int j=0;j<respectively.size();j++)
22 {
23 cout<< respectively[j]<<endl;
24 }
25 */
26 return 0;
27
28
補充說明(Supplement):
我之前也遇過Segmentation fault (core dumped),我認為應該是vector或string的空間
不夠,但vector和string都從0開始,想了又試了好久都無解,想請問各位大神QQ,感激
不盡!!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.116.91.168
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1512044206.A.46A.html
※ 編輯: gn00771771 (140.116.91.168), 11/30/2017 20:17:41
※ 編輯: gn00771771 (140.116.91.168), 11/30/2017 20:18:22
→
11/30 20:36,
8年前
, 1F
11/30 20:36, 1F
可是vector不是可以讓他要輸入多少值來決定自身sizeQQ?
→
11/30 20:37,
8年前
, 2F
11/30 20:37, 2F
這個i是在迴圈內的,表示第幾個元素...不知道大大您的意思是qq?
編輯: gn00771771 (140.116.91.168), 11/30/2017 21:28:25
※ 編輯: gn00771771 (140.116.91.168), 11/30/2017 21:30:17
→
11/30 21:34,
8年前
, 3F
11/30 21:34, 3F
→
11/30 21:35,
8年前
, 4F
11/30 21:35, 4F
→
11/30 21:37,
8年前
, 5F
11/30 21:37, 5F
→
11/30 21:37,
8年前
, 6F
11/30 21:37, 6F
謝謝你love大!我犯了一個大錯,竟把所有東西都push_back到單一string,但是我把[i]
拿掉以後,似乎發現string doesn't have a conversion constructor that accepts
only a single char as input
" invalid user-defined conversion from ‘char’to ‘const value_type&"
我要在想想QQ謝謝love大!!
→
11/30 21:37,
8年前
, 7F
11/30 21:37, 7F
※ 編輯: gn00771771 (140.116.91.168), 11/30/2017 21:55:07
※ 編輯: gn00771771 (140.116.91.168), 11/30/2017 21:55:57
我把vector<string>改成vector<char>就ok了,謝謝各位老師!!
※ 編輯: gn00771771 (140.116.91.168), 11/30/2017 22:00:39
推
12/01 00:11,
8年前
, 8F
12/01 00:11, 8F
我想把一行字串每一個char存在vector的一個元素
推
12/01 00:27,
8年前
, 9F
12/01 00:27, 9F
!!!!慚愧,我不知道vector也有at function
感謝各位老師學長姐QQ
※ 編輯: gn00771771 (140.116.91.168), 12/01/2017 06:05:35
→
12/01 07:41,
8年前
, 10F
12/01 07:41, 10F
→
12/01 07:41,
8年前
, 11F
12/01 07:41, 11F
→
12/01 07:41,
8年前
, 12F
12/01 07:41, 12F
推
12/01 11:50,
8年前
, 13F
12/01 11:50, 13F
推
12/01 13:21,
8年前
, 14F
12/01 13:21, 14F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章