-
Ignoring spaces...
i need to ignore spaces before lines while reading them from a file...the problem is i don't know how many spaces i could get...file could be like this:
Code:
hello
hello
hello
hello
hello
hello
i would rather not do this by first using getline and then getting substrings etc...
can i use ignore effectively here so that when i get the next word from the stream for each line i get hello...
Regards,
Farooq
-
You can use formatted input, which will skip white space for you by default:
Code:
std::string str;
cin >> str;
gg
-
i'm reading from a text file...i know that in >> would read the first word without spaces...i guess that would be sufficient for my problem...
what if i use getline with a delim as ',' implying:
Code:
getline(in, somestring, ',')
this is in the case if i have a file like this:
Code:
2,3 hello
3,4 hello
5,6 hello
1,4 hello
in this case will getline return 2 3 5 1 respectively or would it return these with the amount of spacing before them?
Regards,
Farooq
-
getline will include whitespace, including newlines if ',' is your terminator. Thus it will read " 2" "3 hello\n 3" etc...
If you just wish to trim leading whitespace you can use a manipulator
Code:
std::getline(is>>std::ws,line);
ws acts like a dummy variable that accepts only whitespace, the result of >> applied to a stream is also a stream so we pass that to getline. This is also common when we need to mix parsing formated operations (that leave newlines) and getlines.
-
I had a program awhile ago where I had to convert a string to upper case as well as remove special chars (such as '&')
If you know all your input is going to be an alphabetic character you could consider doing what I did with isalpha();
Code:
int y=0;
for(int i=0; i<(strlen(input)); i++) {
if ( isalpha(input[i]) ) { // remove
message[y] = input[i]; // spaces and
y++; // special chars
}
} // end for loop
What this does is moves the input into a new array which only contains the needed characters. If it is not an alphabetic character, it is not copied.
For spaces you could simply change the if statement to: "if input[i] is a space"
Note: If the message array is shorter than the input array you will have to insert a null character at the end :)