计算TXT文件中元素的数量

Count the number of elements in txt file

本文关键字:元素 TXT 文件 计算      更新时间:2023-10-16

我有这样的作业:

/*
-   Read an input text file (.txt) contain one line to store an array of integer:
Input.txt
4 1 2 -100 -3 10 98 7
-   Write SumList function to sum all integer data of the list
-   Write a function to find the max of all integer data
-   ...
*/

我的问题是如何计算txt文件中的数量数量/for(int i = 0; i< n; i (,n是文件/用于读取文件的数字。还是在不初始化n的情况下读取此文件的其他方法?谢谢!

您的真正问题是:如何通过Word读取文件。

我相信您已经知道什么是文件流,所以这是代码:

fstream file("yourfile.txt", ios::in); 
std::string word;
while (file >> word)
{
    // convert word to int
}

现在下一个问题是:如何将字符串转换为int。我希望您可以自己弄清楚---- http://www.cplusplus.com/reference/cstdlib/atoi/


另外,这将更容易:(感谢@fei Xiang(

int i;
while (file >> i)
{
    // do something
}