我的代码旨在从文件中提取数据," dataset.txt"它确实如此。它能够读取它,将其摄取到我的阵列中并在命令中显示它。
当我尝试搜索我从dataset.txt中提取的数组中的项目时,会出现问题。我的代码似乎无法读取它在那里并且没有显示匹配的结果。
对于任何好奇的人,我的所有数据都是"虚拟数据"从我用来生成虚拟数据的网站。
#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <fstream>
#include <stdio.h>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
int ArraySize = 100; // sets array to 100 items
// initializes all possible arrays in the contact manager
string LastName[ArraySize] = "no data";
string FirstName[ArraySize] = "no data";
string Phone[ArraySize] = "no data";
string Email[ArraySize] = "no data";
string NullOne = "";
// Designed to pull data from the file "dataset.txt"
int i = 1;
std::ifstream myfile;
myfile.open( "dataset.txt", ios::in );
if(!(myfile.is_open())) {
cout << "Error Opening File" << endl;
}
else {
cout << "File can be read. Will pull data." << endl;
}
while(myfile.good())
{
getline(myfile, NullOne);
getline(myfile, LastName[i]);
getline(myfile, FirstName[i]);
getline(myfile, Phone[i]);
getline(myfile, Email[i]);
i++;
}
cout << "Data pull complete!" << endl;
myfile.close();
// Designed to search all data for a specified name string
string NameSearch = "null";
int Matches = 0; // indicates that there is a match at all
cout << "Search for name" << endl;
cout << "Please input name : " << endl;
cout << LastName[4] << endl; // gives me a search parameter to use
cin >> NameSearch;
// search for the name in the Name array
for(int i=0; i<ArraySize; i++) {
cout << LastName[i] << endl;
if (LastName[i] == NameSearch) {
cout << "Name : " << LastName[i] << endl;
cout << "Phone : " << Phone[i] << endl << endl;
Matches++;
}
}
if (Matches == 0) {
cout << "No matches found" << endl << endl;
}
else {
cout << Matches << " matches found" << endl << endl;
}
return 0;
}
它输出的是:
File can be read. Will pull data.
Data pull complete!
Search for name
Please input name :
Chaney
Chaney
no data
Walton
Young
English
Chaney
Carpenter
Castaneda
Potter
Blackwell
Carter
Dyer
Yates
Bentley
Pitts
Dawson
Christensen
Goodwin
Boone
Dunn
Booth
Holman
no data (it displays this for about 40 more lines, I cut it out)
No matches found
它应该找到的匹配是:
Chaney
Penelope
(518) 996-0514
eget@iaculis.edu
我知道这是一种肮脏的方法,我有计划清理它,但我无法让它工作。
答案 0 :(得分:0)
看起来非常像你在从文件中读取的字符串的末尾拾取回车\r
字符。
std::getline
会读取但不包括行尾字符\n
(例如,参见cppreference处的第二个条目),但Windows下的文本文件通常会以两个字符序列\r\n
。
您可以通过检查您读入的字符串的最后一个字符是否实际上等于\r
来确认这是否是问题。如果是这样,可以通过修剪最后一个字符来修复它,例如使用字符串pop_back
方法。