我正在使用 Atoi 的 If 语句苦苦挣扎

I'm struggling with my If-statement using Atoi

本文关键字:If 语句 挣扎 Atoi      更新时间:2023-10-16

我正在尝试制作工单客户代码,我目前正在显示我的"客户"。我希望它像,如果我输入"空白,像什么都没有然后输入",我希望我自己的 DTA 文件中的所有客户都在我的输出中。换句话说,显示,以查看哪些客户已注册。

void Customer::DisplayCustomer() {
    cin.getline(buffer, MAXTEXT)
    buffernr = atoi(buffer)   //I need to convert text to numbers. 
    if (buffer[0]=='A' && buffer[1] == '')
    // (Here I have a function which displays everything) don't focus on this one
}

我要问的是,我必须键入什么,以便我的代码理解我希望为按 Enter 而不键入任何内容的人提供一个 if 语句,我的显示客户函数将运行。我也试过(如果缓冲区[0]==''(,但这也不起作用。

似乎您想为您的用例使用std::getline()而不是std::istream::getline()

void Customer::DisplayCustomer() {
    std::string buffer;
    std::getline(std:cin,buffer);
    std::istringstream iss(buffer);
    int buffernr;
    if(!(iss >> buffernr)) { // This condition would be false if there's no numeric value
                             // has been entered from the standard input
                             // including a simple ENTER (i.e. buffer was empty)
         // (Here i have a function which displays everything) don't focus on this 
         //  one
    }
    else {
        // Use buffernr as it was parsed correctly from input
    }
}

此代码检查缓冲区是否为空

#include <iostream>
int MAXTEXT{300};
int main() {
    char buffer[MAXTEXT];
    std::cin.getline(buffer, MAXTEXT);
    if (buffer[0] == '') {
        std::cout << "Empty" << std::endl;
    }
    return 0;
}

更好的std::string解决方案是

#include <string>
#include <iostream>
int main() {
    std::string buffer;
    std::getline(std::cin, buffer);
    if (buffer.empty()) {
        std::cout << "Empty" << std::endl;
    }
    return 0;
}