theITguy theITguy - 1 month ago 7
C++ Question

Adding elements to array but printing wrong values

I have written this program in C++ that reads an input.txt file containing these numbers
7
18
5
15
131
11
13
287

The program adds to the array the first value 7, then in the next seven numbers there's random values (such as 0, 4659174, 0, 4778144 etc) and then it prints 7 and 18 and then eight more random numbers and then you can see printed 7, 18, 5 and so on until the last eight numbers are what is actually in the input.txt file.

How can I get it to show only the numbers that are present in the input.txt file instead of all of these random values? Here's my code so far:

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <stdlib.h>

using namespace std;

int main(){
int myArray[10];
int i = 0;
ifstream input("input.txt");
string number = "";
char next_letter = '\0';

while (input.get(next_letter)){
while (isdigit(next_letter) && !input.eof()){
number += next_letter;
input.get(next_letter);
}

int val = 0;
val = atoi(number.c_str());


myArray[i++] = val;

for(int i = 0; i < 8; i++)
{
cout << "array contents are: " << myArray[i] << endl;
}
number = "";
}

return 0;
}

Answer

Please consider the following code:

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <stdlib.h>
#include <cstdlib>

using namespace std;

int main(){
    long myArray[10];
    int i = 0;
    ifstream input("input.txt");
    string number = "";
    const int MAX_LEN = 100;
    char number_str[MAX_LEN];

    while(input.getline(number_str, MAX_LEN - 1, ' ')){
        char* end;
        myArray[i++] = std::strtol(number_str, &end, 10);
    }

    cout << "array contents is: ";
    for(int k = 0; k < i; k++)
    {
        cout << myArray[k] << " ";
    }

    cout << endl;
    return 0;
}

The getline does the reading until the ' ' and conversion is done by strtol. Please note that it input numbers are long int by default.

Comments