开发者

First character disappearing in ifstream

Why does this code print the char, without first character?? It says ocalhost instead of localhost. Grateful for help.

#include <winsock2.h>
#include <mysql/mysql.h>
#include <iostream>
#include <windows.h>
#include <fstream>
using namespace std;

int main ()  {    
int b = 0;
char * pch;
int stringLength = 0;
char textRead[50];
ifstream infile("config.ini", ios::in | ios::binary);            
if(!infile) {
            cout << "ERROR: config.ini not found!\n";
            system("pause");
            exit(0);
}

infile >> textRead;
stringLength = strlen(textRead);
pch=strchr(textRead,'"');
while(pch != NULL) {
          infile.seekg(pch-textRead-1);
          infile >> textRead;
          pch = strchr(pch+1,'"开发者_JAVA技巧');
}
cout << textRead;
infile.close();


Inside your while loop you call:

  infile >> textRead;
  pch = strchr(pch+1,'"');

When you try to run strchr in the second line, it's still referring back to the previous string you had in textRead NOT the most recently extracted word.

Unfortunately I can't deduce what you're actually trying to do so I can't offer suggestions on how to fix it.


I'm guessing at the contents of config.ini, since you didn't provide it, but it looks like the ifstream is reading just fine. put a cout << textRead << endl; after your infile >> textRead; to check. This is what I'm using for config.ini:

localhost = "foo"

Your logic with seekg and friends seems broken, though. seekg isn't meant to be used to support parsing (in your case, skipping quotes); it's meant to skip over large chunks of file when needed so you don't waste time reading it in. Honestly, I'm not sure what you're doing since pch-textRead-1 could be -1 if the first character is a quote.

Another thing is that infile >> textRead; does not read a line, it reads a word, and discards leading whitespace.

For the record, I omitted

#include <winsock2.h>
#include <mysql/mysql.h>
#include <windows.h>

since it isn't needed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜