Dr.WallMart Dr.WallMart - 2 months ago 13
C++ Question

Putting a String from a text into an array, using scanf

I'm having some problems reading a string into an array. my file contains the following strings running horizontally down the page.

File:

dog
cat
rabbit
mouse


Code:

#include <string>
int i = 0;
using namespace std;
int main()
{
FILE * input1;
fopen_s(&input1, "C:\\Desktop\\test.dat", "r");
string test_string;
while (!feof(input1)) {
fscanf_s(input1, "%s", test_string);
i++;
}
return 0;
}


Any advice would be appreciated, Thanks!

Answer

You should use ifstream and std::getline

Now, I'm going to walk you through reading lines from the file using ifstream

Include fstream to use ifstream.

#include <fstream>

Opening a file:

To open a file, create an object of ifstream, and call it's method open and pass the filename as parameter. ifstream opens a file to read from it. (To write in a file, you can use ofstream)

ifstream fin;
fin.open("C:\\Desktop\\test.dat");

Or you can simply pass the filename to the constructor to create an object of ifstream and open a file.

ifstream fin("C:\\Desktop\\test.dat");

Reading from the file:

You can use stream extraction operator (>>) to read from the file, just like you use cin

int a;
fin >> a;

To read a line from a file using the above created fin (using a char array)

char arr[100];
fin.getline(arr, 100);

Better yet, you should use std::string instead or char arrays, using std::string, you can read a line using std::getline

string testString;
getline(fin, testString);

Now, let's change your code to use ifstream and getline

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

int main()
{
    int i = 0;
    ifstream input1;
    input1.open("C:\\Desktop\\test.dat");
    string test_string;

    while (getline(input1, test_string)) {
        i++;
    }

    return 0;
}
Comments