C++程序未按预期输出(使用 .at、if/else、getline)

C++ Program Not Outputting as expected (using .at, if/else, getline)

本文关键字:if at else getline 使用 程序 输出 C++      更新时间:2023-10-16

由于某种原因,我的原型程序没有按预期输出。

我的文本文件:(用制表符分隔(

NameOne NameTwo NameThree   56789 

我的源代码:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
    string name1, name2, name3, name4, name5,fullName;
    ifstream inFile;
    string attendance;
    int index;
    inFile.open("test2.dat");
    getline(inFile, name1, 't');
    getline(inFile, name2, 't');
    getline(inFile, name3, 't');
    if (name3.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    {
        attendance = name3;
        fullName = name1 + ' ' + name2;
    }
    else
    {
        getline(inFile, name4, 't');
        if (name4.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
        {
            attendance = name4;
            fullName = name1 + ' ' + name2 + ' ' + name3;
        }
        else
        {
            getline(inFile, name5, 't');
            if (name5.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
            {
                attendance = name5;
                fullName = name1 + ' ' + name2 + ' ' + name3 + ' ' + name4;
            }
            else
            {
                fullName = name1 + ' ' + name2 + ' ' + name3 + ' ' + name4 + ' ' + name5;
                inFile >> attendance;
            }
        }
    }
    cout << endl << fullName << endl << attendance << endl << endl;
    system("pause");
    return 0;
}

预期输出 :

NameOne NameTwo NameThree 
56789

实际输出:

NameOne NameTwo
NameThree

出于某种原因,它将字符串 NameThree 存储到考勤中并输出它。我期待将 NameFour 存储到出席中。

更改以下内容:

if (name.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

对此:

if (isdigit(name.at(0)))

代码中有两个不同的错误:

  1. if语句的结构不正确(我很惊讶它甚至编译(

  2. 例如,为了检查字符是否是 0 数字,您应该将其与 '0' 进行比较(而不是 0 (

您需要

修复if语句:

if (isdigit(name.at(0)))

对于另一个答案中已经陈述的 if 语句。

现在对于您声明的任务:

"出于某种原因,它将字符串NameThree存储到出席中并输出。我本来以为能把《名四》收纳进去。

这是因为您的前if表达式会通过。

name3.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

不幸的是,评估为true.
其余代码(获取name4等(位于该ifelse块中。
因此,执行if(并执行attendance = name3;(后的所有内容以及其余代码直到 else 块(以及以下cout(的末尾才运行。

请记住,if的工作方式如下:

if (expr)
{
   //run if expr == true
}
else
{
  //run if expr == false
}

并且不要忘记0false,其他所有内容在投射到boolean时都映射到true

如果有人想知道如何

if (name4.at(0) == 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

甚至编译,这是因为 C(以及扩展C++(语言将,定义为二进制运算符,如 /-> .它具有最低的优先级,即左关联性,其结果是右侧的值。所以上面的表达式计算为:

(name4.at(0) == 0, 1) => 1
(1, 2) => 2
...
(8, 9) => 9
if(9) => true

(除此之外,C++甚至允许您覆盖operator, 。强烈建议不要这样做。

在你对此过于生气之前,请记住,这是内联函数在C++早期的早期实现方式,在本机编译器出现之前,你使用一个名为 cfront 的工具将C++转换为 C,然后提供 C 编译器。例如,如果您编写:

inline int List::read() const
{
    int x = *head++;
    if(head == end)
        head = begin;
    return x;
}

然后,当你实际调用该函数时,cfront会插入类似的东西

(__inl_x = *obj->head, ++obj->head, obj->head = (obj->head == obj->end? 
    obj->begin: obj->head), __inl_x)

进入调用表达式。请注意,,分隔列表中的最后一件事是"内联"函数的返回值。不用说,有很多语言结构在内联函数中是不允许的(就像现在有很多语言结构在constexpr函数中是不允许的(。