Question

So Lets say this is what the input file contains

12

Hello

45

54

100

Cheese

23

How would I print it out on the screen in that order. This is what I had but it skips some lines.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    int number;
    string word;
    int loop = 0;
    ifstream infile;
    infile.open("arraynumbers.txt");
    while(infile >> number >> word)
    {
        if( infile >> number)
        {
            cout << number << endl;
        }
        if(infile >> word)
        {
            cout << word << endl;
        }
    }
    return 0;
}
Was it helpful?

Solution

I suggest using www.cplusplus.com to answer these questions.

However, you are on the right track. Since you are just outputting the contents of the file to stdout, I suggest using readline() and a string. If you need to access the numeric strings as ints, use the atoi() function.

Example:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string line;
    ifstream file("arraynumber.txt");
    if (file.is_open()) {
        while (getline(file, line)) {
            cout << line << endl;
        }
        file.close();
    } else cout << "Error opening arraynumber.txt: File not found in current directory\n";
    return 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top