Tabish Saifullah
Tabish Saifullah

Reputation: 570

Unable to convert string into float

I write a code in which I scan character values and store them into an array. I type 'x' to stop scanning characters. Now I put '\0' in the end of array to convert array into string. Now I try to convert this string into float by using std::stof. Here is my code

#include "stdafx.h"
#include<stdio.h>
#include <stdlib.h>
#include <iostream>   
#include <string>     

int _tmain(int argc, _TCHAR* argv[])
{
    char str[100];;
    char rec;  
    char count=0;
    double n;
    std::string::size_type sz;  

    while(1)
    {
        scanf("%c",&rec);
        if(rec=='x')
        {
            str[count]='\0';
            printf("%s\n",str);
            sz = strlen(str);
            float value = std::stof (str,&sz);
            printf("%f",value);
        }
        else
        {
            str[count]=rec;
            count++;
        }

    }
    return 0;
}

But this code is converting only first character into float value. For example , I give input:

1
2
3
.
4
x

My output is :-

1.000000

So, please tell me where is the problem

Upvotes: 0

Views: 361

Answers (2)

tourniquet_grab
tourniquet_grab

Reputation: 911

This problem arises because the input buffer is not cleared. When you press enter, the newline character \n is added to the input buffer. This can be fixed by adding while(getchar()!='\n'); after calling scanf.

In the comments, πάντα ῥεῖ mentioned that using std::cout instead of printf() and std::cin instead of scanf() could simplify your code. It would also fix this issue.

Upvotes: 1

dbrank0
dbrank0

Reputation: 9476

If you really are entering a number with newline after each digit, your should be filtering these newlines out of your string. So use something like:

if (rec != '\n') {
  str[count]=rec;
  count++;
}

Instead of just:

{
  str[count]=rec;
  count++;
}

Upvotes: 0

Related Questions