【发布时间】:2019-02-27 14:02:47
【问题描述】:
文件确实打开了,我收到消息“文件打开成功”。但是,我无法将文件“random.csv”中的数组中的数据输入到我的 inputFile 对象中。
random.csv 中的数据为:
Boston,94,-15,65
Chicago,92,-21,72
Atlanta,101,10,80
Austin,107,19,81
Phoenix,112,23,88
Washington,88,-10,68
这是我的代码:
#include "main.h"
int main() {
string item; //To hold file input
int i = 0;
char array[6];
ifstream inputFile;
inputFile.open ("random.csv",ios::in);
//Check for error
if (inputFile.fail()) {
cout << "There was an error opening your file" << endl;
exit(1);
} else {
cout << "File opened successfully!" << endl;
}
while (i < 6) {
inputFile >> array[i];
i++;
}
for (int y = 0; y < 6; y++) {
cout << array[y] << endl;
}
inputFile.close();
return 0;
}
【问题讨论】:
-
while (i < 6)目的? -
提示:
char array[6]只能容纳 5 个字符(每个 1 个字节) -
不要忘记字符数组应该以 null 结束!
-
更好:不要将
char的数组用于 C++ 中的字符串。使用std::string。 -
@CinCout 一个大小为 6 的字符数组可以容纳 6 个字符。是什么让你觉得有什么不同? OPs 程序中不需要 nul 终止符。