【发布时间】:2010-10-13 13:26:24
【问题描述】:
我正在做一个任务,我应该读取一个文件并计算行数,同时计算其中的单词。 我在 while 循环中尝试了 getline 和 strtok 的组合,但没有奏效。
file:example.txt(要读取的文件)。
嗨,你好,真是个惊喜。
欢迎来到这个地方。
愿您在这里过得愉快。
(3 行,一些单词)。
读取文件.cpp
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
int main()
{
ifstream in("example.txt");
int count = 0;
if(!in)
{
cout << "Cannot open input file.\n";
return 1;
}
char str[255];
string tok;
char * t2;
while(in)
{
in.getline(str, 255);
in>>tok;
char *dup = strdup(tok.c_str());
do
{
t2 = strtok(dup," ");
}while(t2 != NULL);
cout<<t2<<endl;
free (dup);
count++;
}
in.close();
cout<<count;
return 0;
}
【问题讨论】:
-
你需要说的不仅仅是“没用”。告诉我们您遇到了什么错误,或者您的程序执行的操作与您预期的不同,然后提出一个具体问题。我们不会为您调试或重写您的作业。
-
下面的一些示例怎么样:codeproject.com/KB/recipes/Tokenizer.aspx 它们非常高效且有些优雅。字符串工具包库使 C++ 中的复杂字符串处理变得简单易行。