开发者

Reading filecontent pairs of chars into array

开发者 https://www.devze.com 2023-04-10 15:50 出处:网络
In C++, how can I read the contents of a file into an array of strings? I need this for a file that consists of pairs of chars separated by spaces as follows:

In C++, how can I read the contents of a file into an array of strings? I need this for a file that consists of pairs of chars separated by spaces as follows:

cc cc cc cc cc cc
cc cc cc cc cc cc
cc cc cc cc cc cc
cc cc cc cc cc cc

c can be any char, including space! Attempt:

ifstream myfile("myfile.txt");
int numPairs = 24;
string myarray[numPairs];

for( int i = 0; i < numPairs; i++) {
    char read;
    string store = "";

    myfile >> read;
    store += read;

    myfile >> read;
    store += read;

    myfile >> read;

    myarray[i] = store;
}

The problem is that this just skips spaces allto开发者_开发百科gether, hence leading to wrong values. What do I need to change to make it recognize spaces?


That's expected behavior, since operator>>, by defaults, skips whitespace.

The solution is to use the get method, which is a low level operation that reads raw bytes from the stream without any formatting.

char read;
if(myfile.get(read)) // add some safety while we're at it
    store += read; 

By the way, VLAs (arrays with a non constant size) are non standard in C++. You should either specify a constant size, or use a container such as vector.


If the input is exact like you say the following code will work:

ifstream myfile("myfile.txt");
int numPairs = 24;
string myarray[numPairs];

EDIT: if the input is from STDIN
for( int i = 0; i < numPairs; i++) {
    myarray[i] = "";
    myarray[i] += getchar();
    myarray[i]+= getchar();
    getchar(); // the space or end of line

}

EDIT: If we don't now the number of pairs beforehand
      we shoud use a resizable data structure, e.g. vector<string>
vector<string> list;
// read from file stream
while (!myfile.eof()) {
    string temp = "";
    temp += myfile.get();
    temp += myfile.get();
    list.push_back(temp);
    myfile.get();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消