.txt文件转换为字符数组
.txt file to char array?
我一直在尝试读取一个.txt文件,其中包含以下文本:
调试的难度是编写代码的两倍。因此,如果您尽可能聪明地编写代码,那么根据定义,您还没有聪明到可以调试它。——Brian W. Kernighan *
然而,当我尝试将。txt文件发送到我的char数组时,除了"Debugging"这个词外,整个消息都打印出来了,我不知道为什么。这是我的代码。一定是什么简单的事情,我看不出来,任何帮助将不胜感激。
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char quote[300];
ifstream File;
File.open("lab4data.txt");
File >> quote;
File.get(quote, 300, '*');
cout << quote << endl;
}
File >> quote;
将第一个单词读入数组。然后对File.get
的下一个调用复制你已经读过的单词。所以第一个单词丢失了
你应该从你的代码中删除上面的行,它将正常工作。
我通常建议使用std::string
而不是字符数组来读取,但我可以看到ifstream::get
不支持它,最接近的是streambuf
。
另一件要注意的事情是检查你的文件是否正确打开。
下面的代码就是这样做的。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
char quote[300];
ifstream file("kernighan.txt");
if(file)
{
file.get(quote, 300, '*');
cout << quote << 'n';
} else
{
cout << "file could not be openedn";
}
}
对象ifstream
可转换为bool
(或c++03世界中的void*
),因此可以测试其真实性
一个简单的逐字符读取方法(未测试)
<标题>包括#include <fstream>
using namespace std;
int main()
{
char quote[300];
ifstream File;
File.open("lab4data.txt");
if(File)
{
int i = 0;
char c;
while(!File.eof())
{
File.read(&c,sizeof(char));
quote[i++] =c;
}
quote[i]=' ';
cout << quote << endl;
File.close();
}
}
标题>相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?