//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
用于命名不明确的较小程序是很好的,但在大型程序中最好避免。