从文本文件读取并存储到数组C ++ [英] Read from a text file and storing to an array C++
本文介绍了从文本文件读取并存储到数组C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个程序可以从文本文件(sortarraysin.txt)中读取值,并将这些值存储到数组中。但是,当我尝试将阵列打印到控制台时,我的输出不会显示文本文件中的数字。我的文本文件和程序如下所示。
I have a program that reads values from a text file(sortarraysin.txt) and stores those values into an array. However when I try to print the array to the console my output does not display the numbers from the text file. My text file and program are shown below.
文本文件:
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
为什么我的数组值打印这些数字而不是文本文件中的值?
Why are my array values printing these numbers instead of the values from the text file?
推荐答案
int value;
int i = 0;
while(inFileStr >> value)
{
myArray[i] = value;
i++;
}
如果您遵循我的指示,则无需使用getline,并且不需要将字符串转换为整数。记住更少的代码会更快。.
you don't need to use getline if you follow my instruction, and you will not need to convert string to integer. Remember less code is faster..
这篇关于从文本文件读取并存储到数组C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文