First character disappearing in ifstream

ε祈祈猫儿з 提交于 2019-12-25 01:45:50

问题


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,'"');
}
cout << textRead;
infile.close();

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4218546/first-character-disappearing-in-ifstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!