因此,我正在尝试编写一个可以从文件读取数据的程序。该文件由整数,字符和双精度数组成。而且我必须能够将它们分配给不同的变量以进行进一步的计算(这实际上只是更大程序的一部分)。我已经在网上搜索了(这里也是),并且看到了不同的解决方案。串流,向量和诸如此类。我最喜欢的那个是在阅读时使用“ skipws”。但是我似乎无法正确读取整数。
我希望有一种解决方案,要求使用尽可能少的方法(流,获取等)。但是,如果我需要更多,我可以忍受。
#include <iostream>
#include <fstream>
#include <cstring>
using namespace::std;
int main()
{
int j = 0, kill = 0, i;
char initials[10];
int results[10];
double avg;
ifstream read("P1.txt");
if (!read) //test to see if file can be opened.
{
cerr << "Error" << endl;
exit(1);
}
while(kill != 1) //kill = 1 same as eof. Just my weird way of coding.
{
switch (j)
{
case 0: //read the first line of data, which is the chars.
read >> skipws >> initials;
j++;
break;
case 1: //read the second line of data, which is 10 integers and whitespace
for (i=0;i<10;i++)
read >> skipws >> results[i];
j++;
break;
case 2: //read the last line which is a single double.
read >> skipws >> avg;
j++;
break;
case 3: //check for end of file.
if(read.eof() == 0)
kill = 1;
break;
}
}
//the 3 lines below are just writing the contents of the file to the prompt.
//It's to check that values are stored correctly for further use.
cout << initials << endl;
cout << results << endl;
cout << avg << endl;
return 0;
}
我确切知道y输入文件“ P1.txt”是什么样子,因为我是在程序的另一部分中自己创建的。看起来像这样:
ccs
2 4 5 3 1 4 6 1 1 1
2.8
这3行给了我一个球员的名字缩写,他10场比赛的结果以及他的平均得分。简而言之,一个玩家的数据。在最终程序中,我需要能够读取大约10个玩家的值。
我期望最后的3条提示行显示如下:
ccs
2453146111
2.8
现在,据我所知。如果我将results [10]声明为char,则可以在控制台中获取它:
ccs
2453146111ccs
2.8
如果我将其声明为int,我会得到这个
ccs
0x7fff5fbff6c0
2.8
显然,我可以看到值存储不正确并且有些东西失控,但是我需要其他人对此进行关注。我没有头绪。
我知道这是一种麻烦的方法,可以在较小的空间内完成,但是我对C ++并不陌生,所以这对我来说很有意义,并且直到现在我也很容易找到我的错误。
我尽力解释了一下。这是我在这里的第一篇文章,所以请告诉我是否需要更多信息。
提前致谢!!克里斯。
当result为int [10]并且您使cout <<结果<< endl时,它将打印出数组内存地址,您应该在每次迭代中进行循环以打印result [i]。
for(i=0;i<10;i++){
cout<< result[i];
}
它会给出正确的结果
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句