简体   繁体   中英

Char to Integer coversion in c++

I am trying to convert a Char to Int in my c++ program,followed some of the answers from this site but its still not working . I have a input file with following data in file ld.txt

4
8 2
5 6
8 2
2 3

>./LD < ld.txt

int main()
{
    using namespace std;
    std::vector<int> nums;
    int i,k;
    char j;
    for(i=0;;i++)
    {
        j=fgetc(stdin);
        int l =j - 48;
        if(feof(stdin))
            break;
        nums.push_back(l);
        cout<<nums[i]<<endl;
    }
}

Output is:

4 
-38 
8 
-16
2
-38
5
-16
6
-38
8
-16
2
-38
2
-16
3
-38

Not sure why i am getting the negative numbers

The negative numbers in your output represent characters in your input file that have a value of less than 48. Specifically, space ( ' ' or 32) and newline ( '\\n' or 10) are each less than 48.


Here are other ways to read in a list of integers from a file:

// UNTESTED
int main () {
   int i;
   std::vector<int> results;
   while ( std::cin >> i )
       results.push_back(i);
}

or

// UNTESTED
int main () {
    std::vector<int> results;
    std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
      std::back_inserter(results));
}

or this

// Thanks, WhozCraig
int main () {
    std::vector<int> results((std::istream_iterator<int>(std::cin)),
        std::istream_iterator<int>());
}

-38 = 10 - 48 ie -38 = '\\n' - '0'

In C (and C++ as well) you can use character literals as integers.

You can skip invalid chars testing the value read:

#include <cctype>

if (isdigit(j)) ...

This should be what you are looking for

int main() {
    vector<int> nums;
    int i,k;
    char j;
    while(cin >> j){
        int l =j - 48;
        nums.push_back(l);
    }
    for(int i =0; i < nums.size(); i++)
        cout << nums[i] << " ";
    cout << endl;

}

The thing is, cin ignores the white space and new line characters. I've never used fgetsc before, but I'm guessing that it doesn't not ignore the white space/newlines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM