我在使用Atoi的If陈述而苦苦挣扎

时间:2019-04-06 22:53:37

标签: c++ if-statement atoi

我正在尝试制作机票客户代码,并且目前正在显示“客户”。我希望它像是,如果我键入“空白,什么也不想输入,请输入”,我希望我自己的DTA文件中的所有客户都在我的输出中。换句话说,显示注册了哪些客户。

void Customer::DisplayCustomer(){

cin.getline(buffer, MAXTEXT)
buffernr = atoi(buffer)   //I need to convert text to numbers. 

if (buffer[0]=='A' && buffer[1] == '\0')
// (Here i have a function which displays everything) don't focus on this 
//  one
}

我要问的是,我必须键入什么,才能让我的代码理解我想为按下Enter键但不键入任何内容的人提供if语句,我的显示定制器功能将运行。我也尝试过(如果buffer [0] =='\ n'),但这也不起作用。

2 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:-2)

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

#include <iostream>

int MAXTEXT{300};

int main() {
    char buffer[MAXTEXT];
    std::cin.getline(buffer, MAXTEXT);
    if (buffer[0] == '\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;
}