【发布时间】:2017-11-09 00:02:40
【问题描述】:
我有一个程序从文本文件 (sortarraysin.txt) 中读取值并将这些值存储到一个数组中。但是,当我尝试将数组打印到控制台时,我的输出不显示文本文件中的数字。我的文本文件和程序如下所示。
文本文件:
45 59 302 48 51 3 1 23
程序:
int array[8];
int i = 0;
string inFileName, getcontent;
cout << "Enter input file name -> ";
cin >> inFileName;
fstream inFileStr(inFileName.c_str(), ios::in);
if(inFileStr.fail()){
cerr << "Unable to open " << inFileName << endl;
exit(-1);
}
if(inFileStr.is_open()){
while(!inFileStr.eof()){
getline(inFileStr, getcontent);
cout << getcontent << endl;
array[i++] << atoi(getcontent.c_str());
for(i=0;i<=8;i++){
cout << array[i] << " ";
}
}
}
输出:
Enter input file name -> sortarraysin.txt
45 59 302 48 51 3 1 23
-2145069216 1 -13232 0 -2145069216 1 -12816 0 -13136
为什么我的数组值打印的是这些数字而不是文本文件中的值?
【问题讨论】:
-
那么,为什么不把数字读成数字呢?可能也想阅读此内容:stackoverflow.com/questions/5605125/… 如果您的所有数字都在同一行并且您阅读了整行,那么您需要在将其转换为数字之前对该行进行拆分。但实际上,只需阅读数字..
-
@RetiredNinja 我该怎么做?
-
int num; while(file >> num) { do something with the number }