编程计算文件中空格隔开的单词数目改进程序(附英文答案)似乎有错误

来源:百度知道 编辑:UC知道 时间:2024/05/23 20:16:11
2-3
Create a program that opens a file and counts the whitespace-separated words in that file.

Solution:

The first version opens its own source file:

//: S02:Words.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ifstream f("Words.cpp");
int nwords = 0;
string word;

while (f >> word)
++nwords;

cout << "Number of words = " << nwords << endl;
}

/* Output:
Number of words = 42
*/ ///:~
The <fstream> header defines classes for file IO, including ifstream, whose constructor takes a file name an argument. The expression f >> word extracts the next non-whitespace token from the file and returns the stream. When a stream appears in a boolean context, such as the while statement above, it evaluates to true until end-of-file

第二个程序 是输入一个文件名,
读取其中单词数目,但是并没有上述功能,而且是个死循环,哪位大侠能
改正这个程序 求教~~~~~

你理解错了,
#include <iostream>
#include <string>
using namespace std;
////////////////
while (cin >> word) {
++nwords;
}
一、文件头没有包含fstream,没有实现读取文件的功能,
二、cin>>word表示从键盘输入 单词,不是文件名
三、因为你一直在输入,所以就是死循环,输入完成后按ctrl+z 再加回车,结束输入
我这里已经编译通过。

利用C++如何编程:编写程序,统计一串字符中包含的单词数(假定单词以一个或多个空格分隔)。 c语言中怎么计算一个句子的单词数 编程:求出一字符串中最长的单词。假设字符串中中含有字母和空格,空格是用来分隔不同单词的 程序代码 对存储在字符串变量中的英文句子统计其中的单词个数。单词之间用空格隔开。 我想我把C语言产生的数组给存到文件中去,并且每个数据以空格隔开怎么弄 在Visual C++6.0开发环境中,输入一行字符,统计其中有多少个单词,单词之间用空格隔开。 用PASCAL做!读入一英文句子,单词之间用空格或逗号隔开,统计其中单词个数,并输出各个字母出现的频率。 EXCEL中如何计算空格? 输入一串字符,统计单词个数,单词之间用空格隔开,请问大家用C语言怎么做? C语言问题:输入一行字符,统计其中有多少个单词,单词之间用空格隔开