如何存储具有多个空格的字符串 C++
How to store a string with multiple whitespaces c++
我的程序应该接受一些输入,例如 "Hi there." 或 "I have an a."(注意结束点),如果字符串包含 "a",则输出 "yes"或者 "no" 如果没有。
问题是 cin 会跳过空格,而 noskipws 似乎不起作用。
我得到的代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
string sequence;
cin >> noskipws >> sequence;
for (auto c : sequence) {
if (c == 'a') {
cout << "yes" << "\n";
return 0;
}
}
cout << "no" << "\n";
}
Input: "where are you." Output: nothing
Input: "what." Output: yes
使用 getline() 的解决方案,一如既往的 ῥεῖ 建议:
#include <iostream>
#include <string>
int main()
{
std::string sequence;
std::getline(std::cin, sequence);
for (auto c : sequence) {
if (c == 'a') {
std::cout << "yes\n";
return 0;
}
}
std::cout << "no\n";
}
您可以使用 std::getline() 或者如果您想要逐字 select 可以试试这个。
#include <iostream>
#include <string>
int main(){
std::string sequence;
while(std::cin >> sequence){
for (auto c : sequence) {
if (c == 'a') {
std::cout << "yes\n";
return 0;
}
}
}
cout << "no" << "\n";
return 0;
}
我的程序应该接受一些输入,例如 "Hi there." 或 "I have an a."(注意结束点),如果字符串包含 "a",则输出 "yes"或者 "no" 如果没有。 问题是 cin 会跳过空格,而 noskipws 似乎不起作用。
我得到的代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
string sequence;
cin >> noskipws >> sequence;
for (auto c : sequence) {
if (c == 'a') {
cout << "yes" << "\n";
return 0;
}
}
cout << "no" << "\n";
}
Input: "where are you." Output: nothing
Input: "what." Output: yes
使用 getline() 的解决方案,一如既往的 ῥεῖ 建议:
#include <iostream>
#include <string>
int main()
{
std::string sequence;
std::getline(std::cin, sequence);
for (auto c : sequence) {
if (c == 'a') {
std::cout << "yes\n";
return 0;
}
}
std::cout << "no\n";
}
您可以使用 std::getline() 或者如果您想要逐字 select 可以试试这个。
#include <iostream>
#include <string>
int main(){
std::string sequence;
while(std::cin >> sequence){
for (auto c : sequence) {
if (c == 'a') {
std::cout << "yes\n";
return 0;
}
}
}
cout << "no" << "\n";
return 0;
}