Replace space with an underscore

I am trying to write something that replaces all spaces in a string with an underscore.

What I still have.

string space2underscore(string text)
{
    for(int i = 0; i < text.length(); i++)
    {
        if(text[i] == ' ')
            text[i] = '_';
    }
    return text;
}

For the most part, this would work if I did something like.

string word = "hello stackoverflow";
word = space2underscore(word);
cout << word;

This will output "hello_stackoverflow", which is what I want.

However, if I did something like

string word;
cin >> word;
word = space2underscore(word);
cout << word;

I would just get the first word "hello."

Does anyone know about this?

+5
source share
5 answers

The problem is that cin >> wordonly the first word will be read. If you want to work as a unit, you must use std::getline.

For instance:

std::string s;
std::getline(std::cin, s);
s = space2underscore(s);
std::cout << s << std::endl;

In addition, you can check if you were really able to read the line. You can do it like this:

std::string s;
if(std::getline(std::cin, s)) {
    s = space2underscore(s);
    std::cout << s << std::endl;
}

, , , . :

std::string space2underscore(std::string text) {
    for(std::string::iterator it = text.begin(); it != text.end(); ++it) {
        if(*it == ' ') {
            *it = '_';
        }
    }
    return text;
}

std::transform!

EDIT: ++ 0x ( , if), lambdas std::transform, :

std::string s = "hello stackoverflow";
std::transform(s.begin(), s.end(), s.begin(), [](char ch) {
    return ch == ' ' ? '_' : ch;
});
std::cout << s << std::endl;
+13

getline, , . :

std::string space2underscore(std::string text)
{
    std::replace(text.begin(), text.end(), ' ', '_');
    return text;
}

, , , .

+10

std::cin iostream: >> std::string, ( ).

std::getline(), .

+5

++ 1x std:: regex_replace.

#include <regex>
#include <string>
#include <cstdlib>
#include <iostream>

using std::cout;
using std::endl;
using std::regex;
using std::string;
using std::regex_replace;

int main( const int, const char** )
{
   const auto target = regex{ " " };
   const auto replacement = string{ "_" };
   const auto value = string{ "hello stackoverflow" };

   cout << regex_replace( value, target, replacement ) << endl;

   return EXIT_SUCCESS;
}

: .

. .

0

cin >> word;

getline(cin, word);
-1

All Articles