第一个字符在ifstream中消失 [英] First character disappearing in ifstream

查看:157
本文介绍了第一个字符在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆