在xcode

时间:2016-04-24 16:55:07

标签: c++ xcode

我在xcode中遇到问题。我正在使用xcode 7.3。我创建了很多程序。但在某些情况下,使用gets / getline函数会产生问题。 在我的一个编码中,获取函数只是跳过而没有任何错误。我试图在其他地方更换它,有时它有效,有时它没有。 这是我的代码:

#include <iostream>
#include<stdio.h>
class TESTMATCH
{

private:
int TestCode, NoOfCandidates, CenterReqd;
    char Description[40];



int CALCULATECNTR()
{
    int x;
    x=NoOfCandidates/100+1;
    return x;
}

public:
void GETDATA()
{
    std::cout<<"Enter Details...\n";
    std::cout<<"Enter Test Code: ";
    std::cin>>TestCode;
    std::cout<<"Enter Description: ";
    gets(Description);
    std::cout<<"Enter No. of Candidates: ";
    std::cin>>NoOfCandidates;


    CenterReqd=CALCULATECNTR();
}

void PUTDATA()
{
    std::cout<<"TEST MATCH INFORMATION \n";
    std::cout<<"Test Match Code\t:"<<TestCode;
    std::cout<<"\nDescription\t\t:";
    puts(Description);
    std::cout<<"\nTotal Candidates\t:"<<NoOfCandidates;
    std::cout<<"\nCentres Required\t:"<<CenterReqd;
}



 }TM1;

int main()
{
char a;
do
{
    TM1.GETDATA();
    TM1.PUTDATA();
    std::cout<<"\nWant to Enter More? Y or N?";
    std::cin>>a;
}while (a=='Y' || a=='y');
}'

这是输出:

Enter Details...
Enter Test Code: 123
Enter Description: Enter No. of Candidates: 3123
TEST MATCH INFORMATION 
Test Match Code : 123
Description     :

Total Candidates    :3123
Centres Required    :32
Want to Enter More? Y or N?n
Program ended with exit code: 0

我不知道该怎么做。我的编译器或代码有问题吗?当我在xcode 6.4和netbeans上运行它时,同样的问题仍然存在,但它在turbo C ++上完美运行。我在输出部分发布的是在xcode的输出控制台中显示的内容。 请帮忙。

1 个答案:

答案 0 :(得分:0)

让我们尝试一个简单的版本来测试一些概念:

#include <iostream>
#include <string>
#include <cstdlib>

int main()
{
    int TestCode = -1;
    std::string Description;
    int NoOfCandidates = -1;

    std::cout<<"Enter Details...\n";
    std::cout<<"Enter Test Code: ";
    std::cin>>TestCode;
    std::cout<<"Enter Description: ";
    std::getline(std::cin,Description);
    std::cout<<"Enter No. of Candidates: ";
    std::cin>>NoOfCandidates;

    std::cout << "\n\nYour entered:\n"
              << "Description: \"" << Description << "\"\n"
              << "Test code: " << TestCode << "\n"
              << "Number of candidates: " << NoOfCandidates << "\n";
    return EXIT_SUCCESS;
}

使用Cygwin和G ++版本5.3.0,我有以下成绩单:

$ g++ -o gets.exe gets.cpp

$ ./gets.exe
Enter Details...
Enter Test Code: 42
Enter Description: Enter No. of Candidates: 25


Your entered:
Description: ""
Test code: 42
Number of candidates: 25

当调用std::getline时,换行符字符仍在输入缓冲区中。让我们更改代码并忽略换行符。

//...
        std::cout<<"Enter Test Code: ";
        std::cin>>TestCode;

/* --> */ std::cin.ignore(1000000, '\n');  // One method to ignore the newline.

        std::cout<<"Enter Description: ";
//...

成绩单:

$ g++ -o gets.exe gets.cpp

$ ./gets.exe
Enter Details...
Enter Test Code: 42
Enter Description: Frog
Enter No. of Candidates: 69


Your entered:
Description: "Frog"
Test code: 42
Number of candidates: 69