[英]Reading a text file and get the result of only the last integer per line in C/C++
好的,我得到了一个文本文件,每行有3个整数。 第一个是文档编号,第二个是单词编号,第三个是单词在该文档中出现的次数。
例如
我的课是使用MPI作为在学校集群中的各个节点之间拆分文本文件的一种方式。 我需要检查每个文档是否包含一个不出现X次的单词,然后返回执行该操作的文档数量。 我是C / C ++的新手,只需要知道最简单的方法是什么。
只需要知道最简单的方法是
我认为您可以尝试以下方法:
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';
}
请确保在以下情况下检查您的解决方案:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.