简体   繁体   English

如何使字符串向量保留用户输入的空格?

[英]How do I make a string vector keep spaces from user input?

I do apologize if this has been asked before, but I haven't really seen this come up in my books or in other examples. 如果确实有人问过这个问题,我对此表示歉意,但是我并没有在我的书本或其他示例中真正看到这一点。 So here I go. 所以我走了。

I have been getting into a card game, after getting lazy with constant shuffling I made a program that does it for me, theoretically. 我一直在玩纸牌游戏,在经过不断的改组后变得懒惰之后,我编写了一个理论上可以为我做的程序。 I realize there are already programs that do so, but where is the fun in that? 我意识到已经有一些程序可以这样做,但是这样做的乐趣在哪里呢? Onto the problem that led to the question. 引发问题的问题。 Whenever I typed in a card with a two or more word name, it chopped off all the words but the first. 每当我输入带有两个或多个单词名称的卡片时,它都会砍掉除第一个单词以外的所有单词。 I have known this to happen but I don't know how to fix it normally. 我知道这种情况会发生,但我不知道如何正常解决。 Let alone how to store "A, the C" in a vector and keep spaces. 更不用说如何在向量中存储“ A,C”并保持空格。

The Question: How do I store a string like "A, the C" in a string and put it in a container and be able to retrieve it with the spaces in tact? 问题:如何将类似“ A,C”的字符串存储在字符串中,并将其放入容器中,并能够在保留空格的情况下检索它? Am I doing something wrong in the code, or am I using the wrong tool for the shed? 我在代码中做错了还是我在棚子上使用了错误的工具?

#include <iostream>
#include <string>

using namespace std;

int main()
{
string example = " ";
cin >> example; //typed eggs and milk, only got eggs
cout << example << endl;

}

Instead of 代替

cin >> example;

use 采用

std::getline(std::cin, example);

cin >> example; will stop reading when it finds a white space. 发现空白时将停止阅读。 std::getline will cotinue reading until a specified delimiter ( '\\n' by default) is found. std::getline将继续读取,直到找到指定的分隔符(默认为'\\n' )为止。

More on std::getline . 更多关于std::getline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM