2013-09-05 127 views
0

我对C++非常陌生,并试图完成第一步。在我的问题中,我需要阅读3个整数,并用它做一些事情。所以,借此整数我写道:在C++中读取输入

int a, b, n; 
scanf("%i%i\n", &a, &b); 
scanf("%i", &n); 

而且我想:

scanf("%i%i", &a, &b); 
scanf("%i", &n); 

但他总是给我当n一些随机的大整数。 输入:

7 13 
1 

TY

如果我写

freopen("input.txt", "r", stdin); 
freopen("output.txt", "w", stdout); 

int a, b, n; 
cin >> a >> b; 
cin >> n; 
printf("%i", n); 
return 0; 

它不工作。与

freopen("input.txt", "r", stdin); 
freopen("output.txt", "w", stdout); 

int a, b, n; 
scanf("%i%i", &a, &b); 
scanf("%i", &n);  
printf("%i", n); 
return 0; 
+0

认为'%d'为* digit *或* decimal *。 – 0x499602D2

+0

@ 0x499602D2这是误导,暗示如果输入是“42”,'%d'将只消耗'4'。 '%d'表示* decimal *(base-10)。 – jamesdlin

+1

任何不使用的理由?那么你可以很容易地std :: cin >> a >> b >> n; –

回答

0

如果您使用的是C++,那么您有没有使用流的原因?

std::cin >> a >> b; 
std::cin >> n; 

要从文件读取,您将使用std :: ifstream。

std::ifstream file("filename.txt"); 
if(file.is_open()) 
{ 
    file >> a >> b >> n; 
    file.close(); 
} 

cppreference.com是一个很好的参考:ifstream

+0

我需要从文件 – PepeHands

+0

@Dima得到一个输入因此你是一个'std :: ifstream'。任何你可以使用'std :: cin'的东西,你可以用任何'std :: istream'来完成。 –

+0

@Dima如果你从一个文件获得输入,那你为什么使用'scanf'而不是'fscanf'? (然而,两者都非常难以使用,http://www.c-faq.com/stdio/scanfprobs.html) – jamesdlin

2

这不是在C一个输入整数的方式++。尝试:

std::cin >> a >> b >> c; 

但是,如果你想要两个的第一行,并在 单独的行第三,你可能想(使用 std::getline)读取一行行:

std::string line; 
std::getline(std::cin, line); 
std::istringstream l1(line); 
l1 >> a >> b >> std::ws; 
if (!l1 || l1.get() != EOF) { 
    // The line didn't contain two numbers... 
} 
std::getline(std::cin, line); 
std::istringstream l2(line); 
l2 >> n >> std::ws; 
if (!l2 || l1.get() != EOF) { 
    // The second line didn't contain one number... 
} 

这将允许更好的错误检测和恢复 (假设输入格式是面向行的)。你应该忘记scanf。这是很难正确使用 ,并不是很灵活。