从C++中的文件输入
Input from a file in C++
我想逐个字符地从文件中读取,并使用以下循环对每个字符执行特定操作:
ifstream in
while(in)
{
ch=in.get();
//some operation
}
我不想在一段时间内阅读条件下的字符,因为那个时光标会移动到下一个位置,我会错过那个字符。问题是文件的末尾没有正确地发出信号,最后一个字符被读取了两次。请给出避免这种情况的方法如果文件中的字符串是军队它被读取为armyy(当我打印时)
char ch;
while(in.get(ch)){ } //or in>>std::noskipws>>c
将是您想要的字符存储在ch
中的正确方式。那有什么问题?
如果你真的想要你想要的方式,那么你可以使用peek()
来查看下一个字符,并执行适当的操作:
char c = in.peek(); //this will give you the next character in the stream
//if its an eof, do appropriate
使用get:的其他重载
while (in.get(ch)) {
// do something with ch
}
或
for (char ch; in.get(ch); ) {
// do something with ch
}
您也可以使用sscanf读取字符。。在该示例中,您可以看到3个输入是从文本中读取的。前两个是字符串,最后一个是浮点。。还可以使用向量来存储值。。希望这个例子能对有所帮助
std::string str;
char buf_1[50];
char buf_2[50];
while(std::getline(in, str))
{
if(sscanf(str.c_str(), "%s %s %f", buf_1, buf_2, &faceStatistics.statistics) == 3)
{
faceStatistics.faceName_1 = buf_1;
faceStatistics.faceName_2 = buf_2;
faceStat_.push_back(faceStatistics);
}
else
std::cout << "No param in string " << str << std::endl;
}
矢量分配
struct Fstat {
std::string faceName_1;
std::string faceName_2;
float statistics;
};
相关文章:
- C++文本文件输入
- C++ 中文件输入输出中的长长 v/s int
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 用空格填充 2D 数组(从文件输入)
- 流对象来表示文件输入,然后是标准输入?
- 用精神解析文件输入
- 从文件输入和输出
- 来自文本文件输入 c++ 的向量
- 如何通过键盘或分数文件输入分数
- 了解文件输入和输出,我可以写入文件,但无法从文件打印
- 词频程序 - 文件输入太大?
- 尝试从 csv 文件输入大量数据时出错
- 如何将文件从文件输入到C 中的矩阵中
- 如何从Windows CMD运行可执行文件并将其传递给文件输入的参数参数和重定向
- 如何解析文本文件并使用构造函数中的文件输入来创建对象的容器
- 这是读取文件输入的正确方法吗?
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- 如何创建一个具有空值、递减编号系统和.txt文件输入值的二维阵列网格
- C 文件输入流循环问题
- 使用对输入整数的文件输入