【发布时间】:2017-03-12 19:04:52
【问题描述】:
我无法将我的代码存储到两个不同的数组中。以下文本文件包含如下格式:name,1,2,3,4,5anothername,6,7,8,9,10...
例如它可能是这样的,我将它命名为 test.txt:
Drake,1,2,3,4,5
Kanye West,6,7,8,9,10
Ka,11,12,13,14,15,16
Young Thug,17,18,19,20
Kendrick Lamar,21,22,23,24,25
到目前为止,这是我的代码:
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main(){
ifstream inputFile;
inputFile.open("test.txt");
if (inputFile.fail()){
cout << "File open error!" << endl;
return -1;
}
string namesarray[25]; //array used to store names
float numbersarray[25]; //array used to store numbers
string line; //string used to read text file
int i = 0; //counter for entire text input
int j = 0; //counter for namesarray
int k = 0; //counter for numbersarray
while(getline(inputFile, line, ',')){
if (line[i] >= 'A' && line[i] <= 'Z'){
namesarray[j] = line;
j++;
}
else{
numbersarray[k] = stof(line);
k++;
}
i++;
}
inputFile.close();
}
我的问题是我无法将所有名称存储到字符串数组中,但数字存储到浮点数组中就好了。我的代码只存储在名字中,然后是一个随机数。例如,如果我创建一个循环来检查名称或数字是否正确存储
for (int a = 0; a < 25; a++){
cout << numbersarray[a] << endl;
}
数字存储得很好,但检查名称时它不会将所有名称都存储在那里。如果我正在检查该行的第一个字母,如果它包含一个字母,它不应该将名称存储在那里吗?我不想使用 isalpha() ,因为它仍然输出相同的问题。
for (int a = 0; a < 25; a++){
cout << namesarray[a] << endl;
}
【问题讨论】:
-
"
string namesarray[25];"? ...您为什么不使用std::vector<std::string>?...另请阅读why usingeof()as loop condition is considered wrong -
我还没有学过向量,但我仍然坚持使用数组。我已经设置了一个与上面类似的 while 循环,例如:while(getline(inputFile, line, ',')) 但我仍然遇到同样的问题。
-
据我所知,
i在这段代码中几乎一文不值。无论如何,如果您真的想将其作为逐行验证并输入中间的std::string和std::istringstream可能会使代码更容易理解。并且认真;一个结构向量,每个都包含一个名称和一个分数向量是正确的方法。 -
我将如何使用 istringstream?