【问题标题】:taking input of a string word by word逐字输入字符串
【发布时间】:2013-08-21 13:20:06
【问题描述】:

我刚开始学习 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” 一切。为什么?我认为他们做同样的事情。那为什么还要麻烦一次又一次地写呢?

【问题讨论】:

标签: c++


【解决方案1】:

(这是为了其他可能参考的人的利益)

您可以简单地使用 cin 和一个 char 数组。 cin 输入由它遇到的第一个空格分隔。

#include<iostream>
using namespace std;

main()
{
    char word[50];
    cin>>word;
    while(word){
        //Do stuff with word[]
        cin>>word;
    }
}

【讨论】:

    【解决方案2】:

    getline 一次存储整行,这不是您想要的。一个简单的解决方法是拥有三个变量并使用 cin 来获取它们。 C++ 会在空格处自动解析。

    #include <iostream>
    using namespace std;
    
    int main() {
        string a, b, c;
        cin >> a >> b >> c;
        //now you have your three words
        return 0;
    }
    

    我不知道你在说什么特定的“操作”,所以我无法帮助你,但如果它正在改变字符,请阅读字符串和索引。 C++ 文档很棒。至于使用命名空间std;与 std:: 和其他库相比,已经有很多说法了。在 StackOverflow 上尝试 these questions 开始。

    【讨论】:

    【解决方案3】:

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

    #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.

    【讨论】:

    • 我尝试用 cin 阅读。但是由于单词之间用空格隔开,cin 似乎只读取了第一个单词。一个简单的 cin t;计算时间;表明。因此我切换到 getline。
    • @jrok 在您提供的代码上出现编译错误。错误:变量“std::istringstream iss”具有初始化程序但类型不完整
    • @zack 你包括&lt;sstream&gt;吗?
    • @jrok 的“iss”是什么?
    • istringstream 到底是什么?修改后的字符串类型?
    猜你喜欢
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    相关资源
    最近更新 更多