第一个字符在ifstream中消失 [英] First character disappearing in ifstream
问题描述
为什么这段代码打印char,没有第一个字符?它表示 ocalhost
而不是 localhost
。感谢您的帮助。
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();
推荐答案
我猜到 config.ini
,因为你没有提供它,但它看起来像 ifstream
正在读。放一个 cout<< textRead<< endl;
来检查。这是我用于 infile>>之后
textRead; config.ini
:
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"
您的逻辑与 seekg
和朋友似乎坏了,虽然。 seekg
不是用于支持解析(在你的情况下,跳过引号);它是为了在需要时跳过大块的文件,所以你不会浪费时间阅读。老实说,我不知道你在做什么,因为 pch-textRead-1
可以是-1,如果第一个字符是一个引号。
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.
另一件事是 infile>
Another thing is that infile >> textRead;
does not read a line, it reads a word, and discards leading whitespace.
对于记录,我忽略了
#include <winsock2.h>
#include <mysql/mysql.h>
#include <windows.h>
因为不需要。
这篇关于第一个字符在ifstream中消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!