简体   繁体   English

Getline字符串输入以创建单词

[英]Getline string input to create a word

I have a program that receives an input and goes character through character to avoid white spaces. 我有一个程序,该程序接收输入并逐个字符地输入字符,以免出现空格。 What I need to do now is get each one of those characters that aren't white spaces and stores them in a string as a word. 我现在需要做的是获取不是空格的每个字符,并将它们作为单词存储在字符串中。

Someone told me that getline stores each character, it has memory: 有人告诉我, getline存储每个字符,它具有内存:

Then create a while loop that has a (!= ' ')condition and then use the string.append('x') function to "add" each character to the string variable you've created until you have a word. 然后创建一个具有(!='')条件的while循环,然后使用string.append('x')函数将每个字符“添加”到您创建的字符串变量中,直到您有一个单词为止。

I understand the concept but I don't know how to actually do it. 我理解这个概念,但是我不知道该怎么做。

Here is a simple application that takes a string and filters out any spaces. 这是一个简单的应用程序,它可以接收字符串并过滤出所有空格。

// reading a text file
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string input;
  stringstream filter;
  cout << "Enter a string \n";
  cin >> input;
  for(int i = 0; i<input.length(); i++){
      if(input.at(i)!=' '){ //Chech to see is it a space or not
          filter << input.at(i); //If not a space add to the stringstream filter
      }
  }
  string output = filter.str(); //Final string with no spaces

  return 0;
}

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

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