2017-07-17 130 views
-3

當我將信息轉換爲整數並打印出數組時,輸出僅爲0。 info中的每個元素都是從文本文件中獲取的字符串形式輸入的數字。例如:513497628 19 4 16 4 7 14 18 15 10 6 6 1 7 17 88 10 79.我使用strtok刪除行中的空格,並將數字輸入到信息中。當我打印出所有的數字都在那裏。我如何讓這些轉換正確?當將字符串數組轉換爲整數數組時,元素變爲0

string info[1000] 
int student[18]; 
for (int i=1; i<18; i++){ 
    //cout << info[i] << endl; 
    stringstream convert(info[i]); 
    convert << student[n]; 
    cout << student[n] << endl; 
    n++; 
} 
+1

是什麼類型'str'?什麼是'n'(以及與'i'相關的情況如何)? – user0042

+0

此代碼不能編譯 – dlatikay

+2

請注意「<<" and">>」之間的區別。 (如果你沒有編寫不必要的通用代碼,編譯器會幫助你。) – molbdnilo

回答

0

字符串流是我最喜歡的工具。它們會自動轉換數據類型(大部分時間),就像cin和cout一樣。這是一個字符串流的例子。這些都包括在庫

string info = "513497628 19 4 16 4 7 14 18 15 10 6 6 1 7 17 88 10 79"; 
int student[18]; 

stringstream ss(info); 

for (int i=0; i< 18; i++){ 
    ss >> student[i]; 
    cout << student[i] << endl;; 
} 

這裏是一個REPL https://repl.it/J5nQ