gpt4 book ai didi

c++ - 从 C++ 文件中读取整数和字符

转载 作者:太空宇宙 更新时间:2023-11-04 16:16:47 25 4
gpt4 key购买 nike

因此,我正在尝试编写一个可以从文件中读取数据的程序。该文件由整数、字符和 double 组成。而且我必须能够将它们分配给不同的变量以进行进一步计算(这实际上只是更大程序的一部分)。我在网上搜索过(这里也是),我看到了不同的解决方案。字符串流、 vector 等等。我用得最远的一个是在阅读时使用“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;
}

我确切地知道你的输入文件“P1.txt”会是什么样子,因为它是我在程序的另一部分自己创建的。它看起来像这样:

ccs
2 4 5 3 1 4 6 1 1 1
2.8

这 3 行给我一个球员的姓名首字母、他 10 场比赛的成绩和他的平均得分。简而言之,一个球员的数据。在最终程序中,我需要能够读取大约 10 个玩家的值。

我期待最后的 3 行 cout 显示:

ccs
2453146111
2.8

现在,这是我所得到的。如果我将 results[10] 声明为 char 我可以在我的控制台中得到这个:

ccs
2453146111ccs
2.8

如果我将它声明为 int 我会得到这个

ccs
0x7fff5fbff6c0
2.8

显然,我可以看到值没有正确存储并且有些东西失控了,但我需要其他人关注这个。我没有线索了。

我知道这样做很麻烦,而且可以在更少的空间内完成,但我是 C++ 的新手,所以这对我来说很有意义,并且让我很容易找到我的错误,直到现在。

我尽量解释清楚了。这是我在这里的第一篇文章,所以如果您需要更多信息,请告诉我。

提前致谢!!克里斯。

最佳答案

当 results 是 int[10] 并且你使 cout << results << endl 它将打印数组内存地址,你应该在每次迭代中循环打印 result[i]。

for(i=0;i<10;i++){
cout<< result[i];
}

它会给出正确的结果

关于c++ - 从 C++ 文件中读取整数和字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21945930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com