如何解决我需要计算给定字符串的每个单词、行和字符
如您所见,我正在尝试获取字数、字符数和行数,但以下代码不起作用。
#include<iostream>
using namespace std;
int main()
{
char ch;
int wc=1,lc=1,cc=0;
while((ch=cin.get())!='*')
{
cc++;
if(ch==' ')
{
wc++;
}
else if(ch=='\n')
{
wc++;
lc++;
}
}
cout<<"\n the number of character=="<<cc;
cout<<"\n the number of words=="<<wc;
cout<<"\n the number of lines=="<<lc;
return 0;
}
解决方法
我输入了您的代码并使用 g++ 对其进行了编译。它工作没有任何问题。你能发布你得到的错误还是编译成功了?
也许你的 Visual C++ 编译器工作不正常。代码本身应该可以工作。
编辑:下面是上述代码的不同版本,其中没有文本输入作为零字串接,并且 EOF 也是循环的中断条件。
EOF 取决于您的系统,在 Windows 上是 Control + z,在 Linux 上可能是 Control + d。
输入文本可能在单词之间有多个空格。标点字符和数字 (0-9) 尽可能作为单词分隔符进行串接。下划线、反引号、波浪号和撇号(如“don't”)作为单词的一部分处理。
大括号作为单词的一部分处理以保持代码简单,但普通括号是分隔符。
#include <iostream>
using namespace std;
int main()
{
int ch,wc=0,lc=1,cc=0,old=0;
cout<<"Enter your text,exit with '*':\n";
while ((ch=cin.get())!='*' && ch!=EOF)
{
cc++;
if (old<='?' && old!='\'')
wc += !(ch<='?' && ch!='\'');
lc += ((old=ch)=='\n');
}
cout<<"\nthe number of character=="<<cc
<<"\nthe number of words=="<<wc
<<"\nthe number of lines=="<<lc<<"\n";
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。