Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to read a file called numbers.txt and insert the integers into an array. My code outputs only the last integer in the file.

//numbers.txt
1
10
7
23
9
3
12
5
2
32
6
42

My code:

int main(){
ifstream myReadFile;
myReadFile.open("/Users/simanshrestha/Dev/PriorityQueue/PriorityQueue/numbers.txt");
char output[100];
int count = 0;
if (myReadFile.is_open()) {
    while (!myReadFile.eof()) {
        myReadFile >> output;
        //cout<< output << endl;
        count++;
    }
    for(int i=0;i<count;i++)
    {
        cout << output[i];
    }
    cout<<endl;
}
cout << "Number of lines: " << count<< endl;
myReadFile.close();
return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

int main()
{
    std::ifstream myReadFile;
    myReadFile.open("/home/duoyi/numbers.txt");
    char output[100];
    int numbers[100];
    int count = 0;
    if (myReadFile.is_open())
    {
        while (myReadFile >> output && !myReadFile.eof())
        {
            numbers[count] = atoi(output);
            count++;
        }
        for(int i = 0; i < count; i++)
        {
            cout << numbers[i] << endl;
        }
    }
    cout << "Number of lines: " << count<< endl;
    myReadFile.close();
    return 0;
}

try this. atoi is a function Convert a string to an integer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...