CODE NOT WORKING - STRING

closed account (ivDwAqkS)
I was trying to develop the function get_number for when I PRESS ENTER it return 0 and when it returns 0 close the program, but when I press enter it doesn't return 0 and still asking me for a number. can someone tell me what is the error in the function get_number()?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;

double get_number();

int main(){
    double n;

    while(true){
        cout << "Enter a num (press ENTER to exit): ";
        cin >> n;/*ERROR WAS THIS, JUST DELETE IT*/
        n=get_number();
        if(n == 0.0){
            break;
        }
        cout << "The squart of " << n << " is " << sqrt(n);

        return 0;
    }
}

double get_number(){
    char s[100];

    cin.getline(s, 100);
    if (strlen(s) == 0){
        return 0.0;
    }
    return atof(s);
}
Last edited on
First, its because cin.getline() gives you the linefeed as well, so you should really check to see if the length is 1 or less. Why don't you use std::string? It works like this, instead:
1
2
3
4
5
6
7
8
9
10
11
#include <string>
//...

double get_number() {
    std::string s;
    std::getline(std::cin, s);

    if (s.size() == 1 && s[0] == '\n')
        return 0.0;
    return std::stod(s);
}


To use std::stod, you need to compile with C++11 compatibility (on GCC or Clang, use -std=c++11). Keep in mind that your compiler might not support std::stod, but all modern compilers should (C++11 has been the standard for more than 2 years now).
closed account (ivDwAqkS)
I Found the ERROR, it was because I typed cin >> n; when n=get_number();was doing it.
closed account (ivDwAqkS)
Thank NT3 for your answer but about what you said, isn't it the same to use atof and atod? and I am compiling with c++, what you wrote is in c code right? because I just read a lil bit of c and it was like that.
Last edited on
Other way round... :)
C-Style strings are used in C, and the headers you are using (cstdlib, cstring and cmath) are all C headers (see the 'c' at the front of the names?). C++ uses the STL, examples of which are iostream, string and vector. atof is a C function for converting C-style strings (char arrays) to a floating point number.
closed account (ivDwAqkS)
NT3 thanks for the explanation, but isn't it the same atof than atod for this case?
Topic archived. No new replies allowed.