简体   繁体   中英

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:

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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