如何使用文件填充数组并将其与用户输入C 进行比较
how do I use a file to populate the array and compare it with user input c++
我编写了一个代码来填充文件的数组然后使用该数组将其与用户输入进行比较该程序应要求用户输入一个名称或部分名称以在大批这是代码:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
bool found = false;
const int arraySize = 35;
const int length = 100;
char contacts[arraySize][length];
int count = 0; // Loop counter variable
ifstream inputFile; // Input file stream object
inputFile.open("input.txt"); // Open the file.
// Read the numbers from the file into the array.
// After this loop executes, the count variable will hold
// the number of values that were stored in the array.
while (count < arraySize && inputFile >> contacts[count])
count++;
// Close the file.
inputFile.close();
char search[length];
char *fileContact = nullptr;
int index;
cout << "To search for your contact's number nplease enter a name or partial name of the person.n";
cin.getline(search, length);
for (index = 0; index < arraySize; index++)
{
fileContact = strstr(contacts[index], search);
if (fileContact != nullptr)
{
cout << contacts[index] << endl;
found = true;
}
}
if (!found) cout << "Sorry, No matches were found!";
return 0;
}
,文件中的名称为
"亚历杭德拉·克鲁兹(Alejandra Cruz(,555-1223"
"乔·鲁尼(Joe Looney(,555-0097"
" Geri Palmer,555-8787"
"李陈,555-1212"
" Holly Gaddis,555-8878"
" Sam Wiggins,555-0998"
"鲍勃·凯恩(Bob Kain(,555-8712"
"蒂姆·海恩斯(Tim Haynes(,555-7676"
"沃伦·加迪斯(Warren Gaddis(,555-9037"
"让·詹姆斯,555-4939"
"罗恩·帕尔默(Ron Palmer(,555-2783"
所以代码有效,但是问题是例如,当我写亚历杭德拉(Alejandra(输出是:"亚历杭德拉输出应该显示全名和数字:"亚历杭德拉·克鲁兹(Alejandra Cruz(,555-1223"
有人知道如何解决这个问题吗?谢谢!!
当您使用
时inputFile >> contacts[count]
- 丢弃了领先的空格字符。
- 非空格字符被读为
contants[count]
。 - 当遇到空格字符时,阅读会停止。
解释您的输出。
您需要改用istream::get
。
while (count < arraySize && inputFile.get(contacts[count], length) )
count++;
回应OP的评论
以上应将文件的所有行高到arraySize
行数。
您可以添加一些调试输出来解决问题。
while (count < arraySize && inputFile.get(contacts[count], length) )
{
std::cout << "Read " << count+1 << "-th line.n" << "t" << contants[count] << "n";
count++;
}
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 用户定义函数中的指针和输入
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 当用户键入分隔符时,停止getline()输入
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 当用户在qtablewidget中输入单元格时,如何获得信号?C++
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 如果用户没有输入任何内容或输入错误,如何重新输入用户的输入?
- 为什么在代码块中执行时会跳过输入用户输入的行?
- 使用 for 循环在数组中输入用户