视觉C++.如何从文件中读取并与输入匹配
visual C++. how to read from file and match with input
我正在尝试读取一个文本文件并将水果与我键入的内容相匹配(例如,我键入 apple,它将在文本文件中搜索单词 apple 并匹配它并输出它已被找到(,但我正在努力实现我想要的结果,因此需要帮助。
我有一个文本文件(水果.txt(,内容如下所示
苹果,30
香蕉,20
梨,10
这是我的代码
string fruit;
string amount;
string line = " ";
ifstream readFile("fruit.txt");
fstream fin;
cout << "Enter A fruit: ";
cin >> fruit;
fin >> fruit >> amount;
while (getline(readFile, line,','))
{
if(fruit != line) {
cout <<"the fruit that you type is not found.";
}
else {
cout <<"fruit found! "<< fruit;
}
}
请告知谢谢。
在循环中,getline
第一次循环line
读"apple"
,第二次读line
"30nbanana"
,依此类推。
而是阅读整行(使用 getline
(,然后使用 例如 std::istringstream
提取果实和数量。
像这样:
std::string line;
while (std:::getline(readFile, line))
{
std::istringstream iss(line);
std::string fruit;
if (std::getline(iss, fruit, ','))
{
// Have a fruit, get amount
int amount;
if (iss >> amount)
{
// Have both fruit and amount
}
}
}
我首先要说的是,我只是像你一样的初学者,拿走了你的代码并进行了一些更改,例如:
-
使用"fstream"从文件读取,直到不是文件的末尾。
-
然后将每一行读入字符串流,以便我以后可以使用逗号分隔符制动它。
-
我还使用了一个二维数组来存储水果和每种类型的数量。
-
最后,我不得不在数组中搜索我要显示的水果。
在我发布代码之前,我想警告您,如果有超过 20 种水果具有多个属性(在本例中为数量(,该程序将无法运行。代码如下:
#include <sstream>
#include <fstream>
#include <iostream>
#include <stdio.h>
using namespace std;
void main (void)
{
fstream readFile("fruit.txt");
string fruit,amount,line;
bool found = false;
string fruitArray[20][2];
cout << "Enter A fruit: ";
cin >> fruit;
while (!readFile.eof())
{
int y =0 ;
int x =0 ;
getline(readFile,line);
stringstream ss(line);
string tempFruit;
while (getline(ss,tempFruit,','))
{
fruitArray[x][y] = tempFruit;
y++;
}
x++;
}
for (int i = 0; i < 20; i++)
{
for (int ii = 0; ii < 2; ii++)
{
string test = fruitArray[i][ii] ;
if (test == fruit)
{
amount = fruitArray[i][ii+1];
found = true;
break;
}
else{
cout <<"Searching" << 'n';
}
}
if (found){
cout << "Found: " << fruit << ". Amount:" << amount << endl;
break;
}
}
cout << "Press any key to exit he program.";
getchar();
}
希望你从中学到了一些东西(我确实学到了(。
相关文章:
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 套接字读取后,我在缓冲区中看到意外输入
- 从标准输入读取文件后读取用户输入
- C++ 从标准输入读取文件名
- 从标准输入读取多个类型时出现问题
- 使用 fgets() 从键盘读取时从以前的输入读取换行符
- 从标准输入读取时zmq_poll不侦听信号
- 从超强的AndroidAudioIO输入读取缓冲区
- 如何实现将用户输入读取到提供的所有变量中的可变参数模板
- 如何使用重定向的标准输入读取文件,即cin(注意:不使用ifstream)
- 将空格分隔的输入读取到C++中的数组中
- Win32 - 从标准输入读取超时
- 从标准输入读取输入,并准备接收来自服务器的广播
- 终止将输入读取到int中的内容
- 如何从标准输入读取输入,直到按下空格或选项卡
- DirectX 11输入读取方法
- 将输入读取到动态大小的数组中