C++ 如何获取字符串直到找到空间
您好,如何获取所有字符串直到找到空格,并在For循环的第二轮中将单词推回直到空格,以开始获取空格后的所有字符串,然后再次获取直到找到空格这是我的代码 例如,本句5BBB3 1f a0aaa f1fg3 我想得到bbbb,把_推回一个chars向量,然后把_推回aaaa,依此类推 字符向量=向量。[0]='bbbb'向量。[1]='aaaa'向量。[2]='f'向量。[3]='ffg' 提前谢谢你 这是我的两个代码都不起作用C++ 如何获取字符串直到找到空间,c++,string,C++,String,您好,如何获取所有字符串直到找到空格,并在For循环的第二轮中将单词推回直到空格,以开始获取空格后的所有字符串,然后再次获取直到找到空格这是我的代码 例如,本句5BBB3 1f a0aaa f1fg3 我想得到bbbb,把_推回一个chars向量,然后把_推回aaaa,依此类推 字符向量=向量。[0]='bbbb'向量。[1]='aaaa'向量。[2]='f'向量。[3]='ffg' 提前谢谢你 这是我的两个代码都不起作用 #include <iostream> #include &
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
string sentece;
getline(cin, sentece);
vector<char> words;
for (int i = 0; i < sentece.size(); ++i)
{
while (sentece.substr(i, ' '))
{
if(isalpha(sentece.at(i)))
{
words.push_back(sentece.at(i));
}
}
}
cout << words[0] << '\n';
cout << words[1] << '\n';
cout << words[2] << '\n';
for(const auto& a : words)
{
cout << a;
}
return 0;
}
//==================================================================
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
string sentece;
getline(cin, sentece);
vector<char> words;
for (int i = 0; i < sentece.size(); ++i)
{
while (sentece.at(i) != ' ')
{
if(isalpha(sentece.at(i)))
{
words.push_back(sentece.at(i));
}
if(sentece.at(i) == ' ')
{
break;
}
}
}
cout << words[0] << '\n';
cout << words[1] << '\n';
cout << words[2] << '\n';
for(const auto& a : words)
{
cout << a;
}
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
串句;
getline(cin,sentece);
向量词;
对于(int i=0;i cout我相信这段代码会给你你想要的答案:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string test = "5bbbb3 1f a0aaa f1fg3";
vector<string> words;
for (int i = 0; i < test.size(); i++)
{
string tmp = "";
while (test[i] != ' ' && i < test.size())
{
if (isalpha(test.at(i))){
tmp += test[i];
}
else if (test.at(i) == ' ')
{
i++;
break;
}
i++;
}
words.push_back(tmp);
}
cout << words[0] << '\n';
cout << words[1] << '\n';
cout << words[2] << '\n';
cout << words[3] << '\n';
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串测试=“5BBB3 1f a0aaa f1fg3”;
向量词;
对于(int i=0;i cout可以将字符数组与scanf()一起使用
`
#包括
使用名称空间std;
int main()
{
chars[1000];
scanf(“%[^”]%s”,s);
coutSo有一个明显的错误。向量词;
这是一个字符向量,但是“bbbb”
是一个字符串,所以你不能把它推到一个字符向量上。字符和字符串是不同的东西。你想要的是向量词;
。因此,到目前为止,扔掉代码,从字符串向量开始,再试一次。除此之外,在第一个示例的while循环中,没有任何变化sentece
或i
,所以这东西将永远循环,将相同的sentece.at(i)
字符推入向量,直到耗尽进程内存(这可能需要一段时间,取决于磁盘空间、操作系统和虚拟分页系统).Thank’s,但主要问题是我不知道如何获取所有单词直到空格,并将其推回向量,这些推回的单词将存储在向量的一个索引中?第二个问题是,如果我生成所有字符串,而不是while(sentece.at(i)!=“”),它显示了!=此部分错误的这个错误(操作数类型是不兼容的“char”和“const char*”)。很明显,您还没有理解字符串
和字符
之间的区别。该代码应该是while(sentece.at(i)!=”
因为sentece
是字符串,所以sentece.at(i)
是一个字符。在您理解其区别之前,这对您来说将是非常困难的。是的,我知道我正在学习字符串和流,我正在通过编写一些代码来理解它。感谢您的帮助。我将更加努力地学习它。再次非常感谢。是的,这对我理解逻辑有很大帮助。谢谢ot和
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[1000];
scanf("%[^' ']%s", s);
cout<<s;
}