读取一个文本文件,只得到 C/C++ 每行最后一个整数的结果
Reading a text file and get the result of only the last integer per line in C/C++
好的,我得到了一个文本文件,每行有 3 个整数。第一个是文档编号,第二个是单词编号,第三个是单词在该文档中出现的次数。
例如
- 1 61 2
- 1 76 1
- 2 89 3
- 3 68 2
我的 class 是使用 MPI 作为在我们学校集群的节点之间拆分文本文件的一种方式。我需要检查每个文档是否包含或不包含出现 X 次的单词,然后 return 出现的文档数量。我是 C/C++ 的新手,只需要知道最简单的方法是什么。
just need to know what the easiest way of doing that would be
我想你可以尝试以下方法:
- 打开 txt 文件。
- 逐行阅读。
- 使用
strtok
从每行中获取每个标记(字符串)。
- 使用
atoi
将最后一个字符串标记转换为 int
。
作为提取最后一个的非常粗略的实现,请看下面的例子:
char str[] = "3 68 2";
char *items[3] = { NULL };
char *pch;
pch = strtok(str, " ");
printf( "pch = %s\n", pch ); // first token
pch = strtok (NULL, " ");
printf( "pch = %s\n", pch ); // second token
pch = strtok (NULL, " ");
printf( "pch = %s\n", pch ); // third token
int i3 = atoi( pch );
printf( "i3 = %d\n", i3 );
您可以使用此代码作为工作的基础。我不想直接解决你的作业问题。
std::ifstream file("myfile");
std::string line;
while (std::getline(file, line)) // for each line in the file, store it in variable line
{
std::istringstream ss(line); // load the line into a string stream for processing
int i; // variable for storing the integers
while (ss >> i) // for each integer successfully extracted
{
std::cout << i << ' '; // print it out
}
std::cout << '\n';
}
请务必根据以下情况检查您的解决方案:
- 空文件
- 空行(无数字)
- 在线1个号码
- 包含非数字的行?
好的,我得到了一个文本文件,每行有 3 个整数。第一个是文档编号,第二个是单词编号,第三个是单词在该文档中出现的次数。
例如
- 1 61 2
- 1 76 1
- 2 89 3
- 3 68 2
我的 class 是使用 MPI 作为在我们学校集群的节点之间拆分文本文件的一种方式。我需要检查每个文档是否包含或不包含出现 X 次的单词,然后 return 出现的文档数量。我是 C/C++ 的新手,只需要知道最简单的方法是什么。
just need to know what the easiest way of doing that would be
我想你可以尝试以下方法:
- 打开 txt 文件。
- 逐行阅读。
- 使用
strtok
从每行中获取每个标记(字符串)。 - 使用
atoi
将最后一个字符串标记转换为int
。
作为提取最后一个的非常粗略的实现,请看下面的例子:
char str[] = "3 68 2";
char *items[3] = { NULL };
char *pch;
pch = strtok(str, " ");
printf( "pch = %s\n", pch ); // first token
pch = strtok (NULL, " ");
printf( "pch = %s\n", pch ); // second token
pch = strtok (NULL, " ");
printf( "pch = %s\n", pch ); // third token
int i3 = atoi( pch );
printf( "i3 = %d\n", i3 );
您可以使用此代码作为工作的基础。我不想直接解决你的作业问题。
std::ifstream file("myfile");
std::string line;
while (std::getline(file, line)) // for each line in the file, store it in variable line
{
std::istringstream ss(line); // load the line into a string stream for processing
int i; // variable for storing the integers
while (ss >> i) // for each integer successfully extracted
{
std::cout << i << ' '; // print it out
}
std::cout << '\n';
}
请务必根据以下情况检查您的解决方案:
- 空文件
- 空行(无数字)
- 在线1个号码
- 包含非数字的行?