White Space and Input

Hello all. I'm working on a problem that takes a double as input and then a unit that comes after such as 12m for 12 meters and 12ft as 12 feet. The problem I've run into is that it wants me to take into account that the user may or may not provide white space between the number and the unit. In other words the user may input "12m" or "12 m". How do I account for this? The only way I've learned to take input so far is "cin >> int >> string" which is okay if the user inputs white space, but what do I do otherwise?

I feel like there has to be a simple way of doing this.

Thanks!
Last edited on
You're in luck - if there is no whitespace, std::cin >> num >> str; will still work as you want.

EDIT: demo http://ideone.com/LS4jT3
Last edited on
but what do I do otherwise?
Same thing. Input for integer will stop as soon as non-digit is encountered (and failbit will not be set if at least one digit was extracted) then string input will extract the rest.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main()
{
    std::string s;
    int i;
    std::cin >> i >> s;
    std::cout << i << ' ' << s;
}
12ft
12 ft
Okay! Thank you so much! I assumed that >> read in values as big chunks that had to be delimited by white space in order for it to work. Also, I'm extremely new to C++, but is simply "string" the same as "std::string"?
It depends on context.
1
2
3
4
5
6
#include <string>

int main()
{
    std::string string = "hello";
}
In the above code, string is a variable, and std::string is a type.
Last edited on
Sorry, I meant something like this:

string word1 = "hello";
std::string word2 = "hello";

Do word1 and word2 have different qualities?
Here are two examples:
1
2
3
4
5
6
7
8
9
#include <string>
using namespace std; //bad practice

int main()
{
    string word1 = "hello";
    std::string word2 = "hello";
    //word1 and word2 have the same type
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>
//using namespace std; //same result whether or not this line is here

struct string
{
    string(std::string const &)
    {
    }
};

int main()
{
    string word1 = "hello";
    std::string word2 = "hello";
    //word1 and word2 have completely different types
}
Okay. Thank you! That helped a lot!
Topic archived. No new replies allowed.