By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,898 Members | 2,012 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,898 IT Pros & Developers. It's quick & easy.

question on whitespace in string

P: 57
I am writing a program that takes input from a user and the program corrects the whitespace and capitalization errors. I have written the part to get the input from the user and stores it in an string with a getline function. My problem is I am tring to figure out a way to check and remove whitespace if anyone can help

thanks

Expand|Select|Wrap|Line Numbers
  1. #include <string>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. int main() {
  6.  
  7.         cout << "enter sentence and hit enter";
  8.         string  s1;
  9.         getline(cin,s1);
this is how i am getting the input in.
Nov 6 '06 #1
Share this Question
Share on Google+
3 Replies


vninja
P: 40
are you looking to get rid of the whitespace before the string or throughout?
for case one you could just add a cin >> fistword; then after the getline st = firstword + st1;
for the second case i'm not too sure....
Nov 6 '06 #2

Expert 100+
P: 1,510
Depends on what you are trying to. You could go thru your string examining each character for correct capitalisation and removing excess whitespace

the C++ <string> class has methods which enable you to iterate thru the contents of a string, repace characters, erase characters, etc. see
http://www.cppreference.com/cppstring/index.html
Nov 6 '06 #3

P: 1
I have had success deleting all whitespace from a given string using the following:

1 #include <iostream>
2
3 void DeleteWS(std::string& x)
4 {
5 for(unsigned int i = 0; i <= x.length(); i++)
6 {
7 if(x[i] == ' ')
8 {
9 x.erase(i, 1);
10 }
11 }
12 }
13 int main()
14 {
15 std::string myString;
16 std::cout << "String: ";
17 getline(std::cin, myString);
18 DeleteWS(myString);
19
20 std::cout << myString << std::endl;
21 }

If anybody notices anything inherently wrong with this code, please let me know.
Jan 25 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.