比较输入值和从文件中读取值的最佳方式
Best way to compare input values to read values from files
我对c++编程还比较陌生,在这一切中我遇到了第一个主要障碍。。
我正试图弄清楚如何从记事本上的通用".txt"文件中读取值/字符。通过比较,我想确定是否读取整行,但我似乎不能只读取单个一位数或两位数,我让它使用{buffername.getline(variable,size)}读取整行,但当我试图将"size"更改为特定数字时,它会给我一个比较错误,说切换到"int"或"char"无效(取决于我如何声明变量)。
感谢您的帮助。感谢
int length = 2;
char * buffer;
ifstream is;
is.open ("test.txt", ios::binary );
// allocate memory:
buffer = new char [length];
// read 2 char
is.read (buffer,length);
//Compare the character and decide
delete[] buffer;
return 0;
您需要使用ifstream
来获取值(ref 1)。
以下内容应该有效。在这里,我使用了一个std::string类型的单词,但您可以用其他类型(即:int、double等)来替换它
std::ifstream f("somefile.txt");
std::string word;
std::string line;
if(f >> word){
if(<the comparison>){
line = f.getline();
}
}
下面是如何使用ifstream 的扩展示例
首先,出于性能原因,一次读取1个字节是个坏主意。
我建议这个替代方案:
最好是整行阅读,然后使用字符数组。
char variable[1000];
将文件中的行读入变量。
if (variable[1]=='c') { printf("Byte 2 (remember 0 offset) is compared for the letter c";}
获得2位数的#
number=((variable[3]-48)*10)+(variable[4]-48);
您必须减去48,因为在ASCII中,数字0是48。
相关文章:
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 从包含 IP 标头片段的二进制文件中读取结构的最佳方法是什么
- 组织从内存读取的数据的最佳方法(用于调试)c++
- 逐行读取QString的最佳方法
- C++,在阻塞模式下从套接字读取所有可用字节的最佳方法
- 读取四个数据文件并使用函数将它们放入结构数组的最佳方法是什么
- 读取内存值(实时)最佳实践
- ifstream是在不使用内存的情况下进行读取的最佳方式
- 读取文本文件而不占用内存的最佳方式
- XE2 - Indy TCPServer:编写和读取列表视图的最佳方式是什么
- 实现QProcess的最佳方法是什么,在"real time"中读取stdout和stderr?
- 在Qt Quick中设置/读取UI值的最佳方式是什么
- 从计数错误的文件中读取数据。读取数据的最佳做法是什么?
- 比较输入值和从文件中读取值的最佳方式
- 从c++中的串行端口读取不同包大小的数据流的最佳方式
- 读取和修改文件的最佳方式(c++)
- c++:读取文件时错误处理(无异常)的最佳实践是什么?
- Winsock -读取、写入、发送和接收套接字的最佳方式
- 从blob SQLite读取二进制图像并使用OpenCV imdecode解码的最佳方法是什么?
- 通过输入重定向读取二进制文件c++的最佳方式