我正在閱讀文件和格式數組,以便我可以用其他的東西來處理它們,但是我一開始就卡住了。它說我不能從char *更改爲char,但我的令牌不是char *。錯誤:無效從'char *'轉換爲'char'行26,36
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <string>
#include <stdio.h>
using namespace std;
void get_input(string teams[][2]) {
string infile;
double value;
char buffer[100];
char token;
stringstream ss;
cout << "Enter the input file: ";
cin >> infile;
ifstream file;
file.open (infile.c_str());
if (file.is_open()) {
int teamcounter = 0;
while (file.getline (buffer, 100)) {
int counter = 0;
token = strtok (buffer, ",");
while (token) {
if (counter == 0) {
teams[teamcounter][counter] = token;
}
else if ((counter == 1) || (counter == 2)) {
ss << token;
ss >> value;
teams[teamcounter][counter] = value;
}
token = strtok (NULL, ",");
counter++;
}
teamcounter++;
}
file.close();
}
else {
cout << "Unable to open file";
}
for (int i = 0; i< 7; i++){
for (int j = 0; j<2;j++){
cout << teams[i][j] << " ";
}
cout << endl;
}
}
正在將我的數組轉換爲字符串使我無法將浮點數或雙精度值給他們嗎?
int main() {
cout << "Welcome to the football bracket game!" << endl;
string teams[7][2];
get_input(teams);
}
我輸入文本格式是這樣的:
Trojans, 0.80, 0.60
Bruins, 0.20, 0.30
Bears, 0.60, 0.50
Trees, 0.50, 0.40
Ducks, 0.40, 0.80
Beavers, 0.50. 0.10
Huskies, 0.80, 0.40
Cougars, 0.10, 0.90
你知道錯誤來自哪裏嗎?你能告訴我們嗎? – 0x499602D2
那麼,當然你不能把一個浮點數或一個double放到char中,但是你可以把一個浮點數或一個double轉換成一個字符串,然後存儲它。錯誤是因爲strtok返回一個char *而你試圖將它存儲在char變量標記中。 –
將令牌聲明爲char *給我分段錯誤。另外,如果我將數字存儲爲字符串,那麼如何將它們用作浮點數? – user3317141