Reputation: 10028
I'm new to C++ and is trying to solve the beginner's problem of trying to remove all punctuation marks from a sentence. Below is the code I have came up with. However, when I entered "Hello! Hello!", the compiler output "Hello" instead of "Hello Hello" (which is what I would expect).
Why is this happening?
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "please enter a sentence which include one or more punctuation marks" << endl;
string userInput;
string result;
cin >> userInput;
decltype(userInput.size()) n;
for (n = 0; n < userInput.size(); n++){
if(!ispunct(userInput[n])){
result += userInput[n];
cout << result << endl;
}
}
return 0;
}
Input:
Hello! Hello!
Compiler output:
Hello
Upvotes: 2
Views: 519
Reputation: 63461
As others already said, you use getline
to read a whole line of text.
I wanted to also point out there are functions in <algorithm>
that make this kind of thing much cleaner. Instead of looping over your string, you can use std::remove_if
.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string line;
while( std::getline( std::cin, line ) )
{
line.erase( std::remove_if( line.begin(), line.end(), ispunct ), line.end() );
std::cout << line << std::endl;
}
return 0;
}
Upvotes: 1
Reputation: 2546
Try using the getline()
function. Read about it here.
Welcome to C++! Read up about stringstreams they are very good at manipulating strings
Upvotes: 1
Reputation: 490048
When you do cin >> userInput
, it only reads up to the first white-space character in the input stream.
You probably want to use std::getline
instead (it'll read the entire line, by default).
Upvotes: 4