C ++初学者:为什么我的编译器根据我的循环返回“找不到名称?”

问题描述 投票:0回答:2

这是我在Java中学习了3个类之后第一次使用C ++进行编程(因此,这里绝对是初学者)。作业提示我添加到文本文件,然后在文本文件中搜索名称(在本例中为我的名字)。它运行得很好,然后我试图让它显示我的全名,而不只是我的姓氏,所以我开始修改它。现在,尽管我输入名称以获得“找到的名称为:”结果,但我仍无法弄清楚为什么结果始终为“找不到名称”。 (此外,作业希望将“找不到名称”添加到其他.txt文件中,因此这就是为什么要使用不同的名称。这很好用。)非常感谢!

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main (){

    ifstream inFile("/Users/katelynwalker/Documents/CSC450_CT5_mod5.txt");
    ofstream outFile;
    outFile.open("/Users/katelynwalker/Documents/CSC450_CT5_mod5.txt", ios::app);//appends instead of overwrites
        outFile<<"Katelyn Walker";
        cout<<"Name has been added to the file. ";
    outFile.close();

    string search;
    cout<<"Please enter a name: ";
    cin>>ws;
    cin>>search;
    bool isFound = 0;
    string name = " ";
    while(getline(inFile, name)){
        for(int i=0; i<search.size(); i++){
            if(name[i]==search[i]){
                isFound = 1;
            }
            else{
                isFound = 0;
            }
        }
        if(isFound){
            cout<<"Name found is: ";
            for(int i=search.size()+1;i<name.size();i++)
                cout << name[i];
        break;
        }
    }
    if(inFile.eof()&&(!isFound)){
        outFile.open("/Users/katelynwalker/Documents/CSC450-not-found_CT5_mod5.txt", ios::app);
        outFile<<"Name not found.";
        cout<<"Name not found.";
    }
    inFile.close();
return 0;
}
c++ loops search append text-files
2个回答
1
投票

如果您希望将姓名写在一行上,则应写完整的一行,包括换行符:

outFile<<"Katelyn Walker" << std::endl;

并且在询问要搜索的名称时,std::cin >> search不允许您输入空格。如果您不需要空格,那没关系,否则您应该使用std::getline(std::cin, search);

与您的问题无关,请不要使用using namespace std;这是一个坏习惯。


0
投票

问题是由cin引起的,它仅使单词到达第一个空格,要使用getline函数获取整个单词。您应该在名称后添加新行,以保持.txt的整洁。另外,您不需要逐字符检查或打印字符串char,您可以只使用整个字符串

int main() {

    ifstream inFile("/Users/katelynwalker/Documents/CSC450_CT5_mod5.txt");
    ofstream outFile;
    outFile.open("/Users/katelynwalker/Documents/CSC450_CT5_mod5.txt", ios::app);//appends instead of overwrites
    outFile << "Katelyn Walker \n";
    cout << "Name has been added to the file. ";
    outFile.close();

   string search;
    cout << "Please enter a name: ";
    cin >> ws;
    getline(cin, search);
    string name = " ";
    while (getline(inFile, name)) {
         if (name.find(search, 0) != string::npos){ //string::npos just meeans null position so not found
         cout << "Name found is: ";
         cout << name;
         }

    }
    if (inFile.eof()) {
        outFile.open("/Users/katelynwalker/Documents/CSC450-not-found_CT5_mod5.txt", ios::app);
        outFile << "Name not found.";
        cout << "Name not found.";
    }
    inFile.close();
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.