2014-01-17 26 views
-4

我是用C++進行編程的新手。 我想詢問用戶(例如)輸入:如何從輸入中獲取某個元素(C++)

std::string numbers; 
std::cout << What is your favorite number; 
std::cin >> numbers 

如果用戶輸入

1, 2, 3 

我如何提取只有數字「2」?我知道在python中,你會做數字[1],但在C++中也有相同的方式嗎?

+0

讀取基本輸入功能:http://www.cplusplus.com/doc/tutorial/basic_io/ – Cristy

+0

@Cristy請不要建議人們閱讀cplusplus教程(和一般的cplusplus),包含非常糟糕和古老的做法。 – Manu343726

+0

你有沒有嘗試過構建你的代碼?因爲你錯過了「」cout – prajmus

回答

2

你可以得到字符串的長度由numbers.length()。

然後你可以使用循環。

for(int i =0 ; i < numbers.length();i++) 
{ 
    if(numbers[i] == '2') 
    // do what you want you do here with 2 
} 

請記住,你的CIN不會得到整個 「1,2,3」,因爲空白的字符串。你應該使用getline而不是cin。

如..

getline(cin, numbers,'\n'); 
3

那麼,「你最喜歡的數字是什麼?」

這個想法和python或其他語言一樣:使用分隔符分割輸入行,如果你在意修剪,最後得到你想要的元素(如果存在的話)。

1

搭上行號:

int main() 
{ 
    std::vector<int> numbers; 
    std::string line; 
    std::getline(std::cin, line);   // First read the whole line of input 

    std::stringstream linestream(line);  // Set up to parse the line 
    int    number; 
    while(linestream >> number) {   // Read a number 
     char x;        // for the comma 
     linestream >> x;      // remove the comma 

     numbers.push_back(number);   // Add to the vector (array) 
    } 

    // Print the number 
    std::cout << "The second number is: " << numbers[1] << "\n"; // vectors are 0 indexed 
} 
相關問題