c++读入一个文本文件,将数据读入到一个字符串中

c++读入一个文本文件,内容格式为“qw we er rt ty yu ui op p”,将数据读入到一个字符串中,再从字符串中读出每个单词保存到string中,求问有什么错误。。。。怎么程序运行会有汉字

根据在Dev C++ 4.9.9.2中的测试,程序应该没有问题。

你可以检查一下q.txt。如果q.txt文件末有多余空行的话,输出可能有问题。

这是因为你使用了sizeof(file)。还有,sizeof(file)确实是文件的大小,这个没有问题。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-07-24
#include <iostream>
#include <fstream>
using namespace std;

int main() {
int t = 0, i, temp;
ifstream file("q.txt");
streampos fsize = file.tellg();  // 得到文件位置
file.seekg(0, ios::end); // 定位至文件末端
size_t filesize = file.tellg() - fsize; // 相差值为文件大小
file.seekg(fsize); // 返回文件开头
char* str = new char[filesize + 1]; // 开空间,注意 + 1
file.getline(str, filesize + 1);
cout << str << endl;
for (i = 0; i < strlen(str) + 1; i++) {
if (str[i] == ' ' || str[i] == '\0') {
temp = i;
char *string = new char[temp - t + 1]; // 这里注意 + 1
strncpy(string, str + t, temp - t);
string[temp - t] = '\0'; // 补回null终结符
cout << string << endl;
t = i + 1;
}
}
}

本回答被提问者和网友采纳
第2个回答  2014-07-24
sizeof(file)是ifstream的对象的大小,并非文件的大小。
这里应该用文件大小。追问

怎么用文件大小啊?

追答

如果文件不是很大,你直接写死一个数字就好了,只要文件大小不超过这个数字(如1024)即可。
文件的大小,要另外的函数(或者流)来获取。

相似回答