1

So I'm trying to write a code for a units converter based on user input for the value and the units. This code sometimes reads the input properly and prints the value and the units correctly, but sometimes it doesn't read either input. It doesn't seem to matter if there is a space between the numbers and the units in the input whether the code reads properly or not. But, I would like the space to not matter(e.g. "12m" vs "12 m")

#include <iostream>
#include <string>

using namespace std;

int main()
{
string units;
double val0 = 0;

cout << "input value and units\n";
cin >> val0 >> units;

cout << "value: " << val0 << "\nunits: " << units << endl;

return 0;
}
Efraín González
  • 201
  • 1
  • 2
  • 5
  • 1
    Take a look at [this](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) question – HMD Apr 10 '18 at 04:21
  • 1
    Have you not tested the code? `12m` works very well, as the m cannot be part of a `double`. So it is left for the next input. – Bo Persson Apr 10 '18 at 09:12
  • @BoPersson I have tested the code. But sometimes when I put 12cm, it doesn't read the input, but it does read 12 cm properly. – Efraín González Apr 10 '18 at 19:33

1 Answers1

2

The way you have it programmed currently, the space will always matter if you are worried about a user breaking your program by using it incorrectly.

If you want the space to be arbitrary, consider using the getline function and implementing your function this way:

string entireLine;
getline(cin, entireLine); //will store either "12 m" or "12m" in entire line
//detect if entireLine contains a space
       //run isSpace() in a loop across every character in entireLine
//parse the string one way if there is a space
//parse the string if there isn't a space
Gunner Stone
  • 997
  • 8
  • 26
  • Is that the only way to make the space arbitrary? It seems like a lot of code to me to have to parse the entire line. I'm doing this problem out of Stroustrup's book, and it hasn't mentioned getline yet but in the prompt, it says "you may consider **12 m**(with a space between the number and the unit) equivalent to **12m**(without the space)". – Efraín González Apr 10 '18 at 19:50