【发布时间】:2020-12-18 23:29:46
【问题描述】:
我想编写代码,从用户那里获取一串文本,并使用 .find () 函数显示字符数和单词数。然后从用户那里获取一个词并搜索文本并显示该词的位置。我现在有麻烦了,请帮帮我。
#include<iostream>
#include <cctype>
#include<string>
#include<cstring>
using namespace std;
int main()
{ char quit;
int word=0;
string txt;
cout << "Enter a string: ";
getline(cin, txt);
cout << "The number of characters in the string is:" << txt.length() << endl;
while(string txt != NULL)
{ if(txt.find(" "))
++word;
}
cout<<"wors is "<<word;
while(quit!='q')
{
cout<<"wors is ";
cin>>search;
cout<<"Enter(c)if you want to continue, and enter(q)if you want quic:";
cin>>quit;
}
return 0;
}
【问题讨论】:
-
while(string txt != NULL) { if(txt.find(" ")) ++word; }-- 如果有多个连续的空格怎么办?即使您修复了代码的string txt != NULL部分,您也会遇到问题。 -
std::string::find返回字符串中的位置,如果找到的话;否则返回std::string::npos。这两个值都可以视为true;但是,如果字符串以空格开头,则位置将为 0,计算结果为 false。
标签: c++ visual-c++ c++17