strings with atoi

I've been trying to read from a file into a string.
Then using atoi add up the ascii values of the characters in the string.
The "atoi" has been giving me values of 0.
Testing later on comfirms the instring values are proper.

1
2
3
4
5
6
7
fstream filestreamin("openfile.txt");
string instring;

while (getline(filestreamin, instring))
{
   strToDigit += atoi(instring.c_str());
}

Why is the atoi failing? How might I remedy this?
What does your text file look like? I did a small test and it worked out fine:

test.txt file
1
2
3
4
5
6
1
2
3
4
5
6


test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cstdlib>
#include <fstream>
#include <iostream>

int main()
{
  std::ifstream in("test.txt");
  std::string buf;
  int sum = 0, count = 0;
  while(std::getline(in,buf))
  {
    sum += atoi(buf.c_str());
    count++;
  }
  std::cout << "Counted " << count << " values with an average of " << std::fixed << (sum/float(count)) << std::endl;
  return 0;
}


output
1
2
3
4
Counted 6 values with an average of 3.500000

Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.
testFile:
The test file consists of a bunch of random c++ related words
1
2
3
4
5
6
7
8
9
10
11
while
foreach
if
then
else
cout
cin
endl
string
int
etc...
Read up on what the atoi function does:

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.


It takes all the digits at the start of the string, and turns them into an integer. Your input strings have no digits in, so none of them will be converted.

You want something like this:

read the word
convert each character individually into its integer representation ( this being C++, static_cast spring to mind)
add those numbers together
Last edited on
Thank you guys. I read through the string and added the (int) of the individual characters, worked like a charm.
:)
Topic archived. No new replies allowed.