2016-11-22 43 views
0

所以我想在同一行輸入多個變量並讓它調用一個函數並將一些變量解析爲它將調用的函數。例如,用戶將輸入類似於如何在同一行上輸入多個變量C++

COMMAND <integer> 

我已經嘗試使用scanf,但是當它確實工作時,它似乎無法識別我通過的變量。我確信我只是犯了一個愚蠢的錯誤,但有人可以幫我嗎?我寫了一個簡單的程序來嘗試測試這樣的傳遞變量,我已經在下面列出了。

#include <iostream> 
#include<stdio.h> 
#include<string> 

using namespace std; 

string derp(int test) { 
    cout << "and here " + test << endl; 
    return "derp " + test; 
} 


void main() { 
    char command[20]; 
    int *bla(0); 
    scanf("%s %u", &command[0], &bla); 
    if (strcmp(command, "derp") == 0) { 
     cout << "works here" << endl; 
     cout << derp(*bla); 
    } 
} 
+1

嘗試的scanf( 「%s%U」 命令,&bla); –

+0

的可能重複[我怎樣在同一行3個整數輸入,並將其保存爲3種不同變量?](http://stackoverflow.com/questions/13437637/how-do-i-get-3-integer-input-on-the-same-line-and-store-it-as-3-different-變量) –

+0

** int * bla ** - > ** int bla **,也許** unsigned int bla **,因爲您正在使用**%u來掃描它** –

回答

0

變化:int *bla(0);從一個指針到一個實際的變量:int bla(0);

也是一樣的輸出:cout << derp(*bla);cout << derp(bla);(不再需要的解引用上BLA)。

此外,你不能輸出一個C字符串+一個int的總和,它不是連接。使用鏈式輸出:

cout << "and here " + test << endl;應該cout << "and here " << test << endl;

return "derp " + test;應固定出於同樣的原因。

修正版本:

#include <iostream> 
#include<stdio.h> 
#include<string> 

using namespace std; 

string derp(int test) { 
    cout << "and here " << test << endl; 
    return std::string("derp ") + to_string(test); 
} 


void main() { 
    char command[20]; 
    int bla(0); 
    scanf("%s %u", &command[0], &bla); 
    if (strcmp(command, "derp") == 0) { 
     cout << "works here" << endl; 
     cout << derp(bla); 
    } 
} 
+0

感謝您的幫助,就像我說的那樣,我覺得這是一件愚蠢的事情,我只是沒有看到。我欣賞第二組眼睛:) – AngelicAlice

相關問題