gpt4 book ai didi

c++ - 逐字输入字符串

转载 作者:IT老高 更新时间:2023-10-28 22:06:39 59 4
gpt4 key购买 nike

我刚开始学习 C++。我只是在玩它,遇到了一个问题,涉及逐字输入字符串,每个单词用空格分隔。我的意思是,假设我有

   name  place animal 

作为输入。我想读第一个单词,对它做一些操作。然后读取第二个单词,对其进行一些操作,然后读取下一个单词,依此类推。

我一开始尝试用 getline 这样的方式存储整个字符串

    #include<iostream>
using namespace std;
int main()
{
string t;
getline(cin,t);
cout << t; //just to confirm the input is read correctly
}

那么我如何对每个单词执行操作并移动到下一个单词呢?

另外,当我在很多地方看到关于 C++ 的谷歌搜索时,人们更喜欢写“std::”而不是使用“使用命名空间 std”一切。为什么?我认为他们做同样的事情。那为什么还要麻烦一遍遍地写呢?

最佳答案

将该行放入字符串流中并逐字提取:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
string t;
getline(cin,t);

istringstream iss(t);
string word;
while(iss >> word) {
/* do stuff with word */
}
}

当然,你可以跳过getline部分,直接从cin中逐字读取。

您可以在这里阅读 why is using namespace std considered bad practice.

关于c++ - 逐字输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18318980/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com