Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 简单C++;否则_C++ - Fatal编程技术网

C++ 简单C++;否则

C++ 简单C++;否则,c++,C++,我试图在文件中插入一个换行符,如果文件中还没有用户提供的int,那么就不应该添加换行符 如果acc==accNum为true,则下面的代码不会添加新条目,但在else块(用于添加新条目)中,会添加相同的多个条目。我最初在时将else移出了,但仍然没有解决问题 while (fin >> acc >> first_name >> last_name >> bal){ if (acc == accNum){ cout <&

我试图在文件中插入一个换行符,如果文件中还没有用户提供的int,那么就不应该添加换行符

如果
acc==accNum
为true,则下面的代码不会添加新条目,但在else块(用于添加新条目)中,会添加相同的多个条目。我最初在时将else移出了
,但仍然没有解决问题

while (fin >> acc >> first_name >> last_name >> bal){
    if (acc == accNum){
        cout << "Account already exist, please check." << endl;
        fin.close();
    } else {

        ofstream fout("bank.txt", ios::app);

        fout << accNum << " " << fname << " " << lname << " " << accBal << endl;
        cout << "New Account Inserted." << endl;

        fout.close();
    }
}
while(fin>>acc>>名字>>姓氏>>bal){
如果(acc==accNum){

cout您可以使用while循环读取数据,并在找到您要查找的内容时设置标志。在while循环之后,检查标志的状态,如果未设置,则执行您拥有的else代码


现在的编写方式是,在每一行不匹配的代码之后,它都会输出新的帐户。根据我建议的更改,我们首先检查整个文件并查找帐户。如果找不到,则插入。

代码与您所做的完全一样。让我们大声读出来:

当输入正确地划分为值时,请执行以下操作:

  • 如果
    acc
    等于
    accNum
    ,请打印“账户已存在,请检查”
  • 如果没有-添加帐户
也许你想要的是:

  • 当输入正确地划分为值时,请执行以下操作:
    • 将所有
      acc
      存储在集合中
  • 检查是否在集合中找到
    accNum
  • 如果是这样,你当然应该使用C++类中的一个提供给你。在你当前的情况下,可能是<>代码> STD::SET < /C>是最好的解决方案,因为它给你线性、摊销时间和在对数时间内的元素的能力。

    因此,您的代码应该更像这样:

    std::set<int> accounts;  // Or any other type instead of int. I'm guessing a bit here
    while (fin >> acc >> first_name >> last_name >> bal)
       accounts.insert(acc);
    if(accounts.count(accNum)
       cout << "Account already exist, please check." << endl;
    else{
       // add the acc to the file
    }
    
    struct account{
       int acc;
       std::string first_name;
       std::string last_name;
       someType bal;
    }
    

    并将它们存储在
    中。如果要将记录存储在
    std::set
    中,则需要重载
    操作符,而无需在析构函数上调用
    close
    ,析构函数将为您执行此操作。