//header
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char** argv)
{
string s,s1=" ";
int i,j,flag=0,flag1=0,count=0;
getline(cin,s);
for(i=0;i<s.length();i++){
if(s[i]==' '){
flag=i;
for(j=flag1;j<flag;j++){
s1=s1+s[j];
flag1=flag+1;
}
//cout<<s1<<" ";--uncommenting this works but below if statement not working
if(s1=="a"||s1=="A"||s1=="an"||s1=="An"){
count++;
}
}
s1=" ";
}
cout<<count;
}
If语句什么都不取,只给出计数值为0
您的s1
被初始化为空白字符,它阻止它与if
语句中的字符串匹配,这些字符串都没有空白字符。
删除多余的两个空白,并将s1
初始化为空字符串。
为了更好地让生活更轻松,您可以在std::stringstream
和std::vector
:的帮助下做同样的事情
#include <iostream>
#include <sstream>
#include <vector>
int main(void) {
std::string string;
std::string temp;
std::vector<std::string> words;
int counter = 0;
std::cout << "Enter a string: ";
std::getline(std::cin, string);
// a string stream to separate each word
std::stringstream ss(string);
// pushing the separated words (by space) into a dynamic array
while (ss >> temp)
words.push_back(temp);
// comparing each array of 'words' (where each separated words are stored
// as a type of 'std::string'
for (size_t i = 0, len = words.size(); i < len; i++)
if (words.at(i) == "a" || words.at(i) == "an" ||
words.at(i) == "A" || words.at(i) == "An")
counter++;
// if no articles found, i.e. the counter is zero
if (counter == 0) {
std::cout << "Sorry, there were no articles found.n";
return 0;
}
// otherwise...
std::cout << counter << " number of articles were found!n";
return 0;
}
样本输出如下:
Enter a string: A great scientist, Newton experimented something on an apple.
// _^___________________________________________________^^_______
2 number of articles were found!
此外,请避免使用bits/stdc++.h
,它既不是标准C++的一部分,也不是@ChrisMM在本文中的评论中所指示的一个好的约定。
对于命名模糊性可以忽略不计的较小程序,使用using namespace std
是很好的,但在大型程序中最好避免。