2014-01-16 92 views
2

我是編程的一般相對新手,我在這段代碼中遇到了問題。C++不能識別空格

cout << "what would you like to have inside that?" << endl; 
cout << "please enter a sentance" << endl; 
cin.sync(); 
cin >> time[d]; 

cout << "Is this what you wrote?" << endl; 
cout << time[d]<< endl; 

system("pause"); 

它不會越過該空間並僅在它之前輸出。

+1

你是什麼意思***不經過空間***? –

+1

getline(std :: cin,time [d])''。就「>>」而言,任何空格都是分隔符。 – cHao

+1

如果你不知道它的作用,請不要使用sync()。此外,格式化的輸入由空白分隔。 – 0x499602D2

回答

4

std::cin認爲所有的空格(空格,換行符,製表符等)是單獨輸入之間的「分隔符」。有幾種方法可以更改分隔符,但您可能更適合getline,默認爲換行符作爲分隔符(儘管您可以選擇指定不同的分隔符)。

0

我相信你正在尋找std :: getline,因爲std :: cin會將任何空格視爲分隔符。試試這個:

#include <iostream> 
#include <vector> 
#include <string> 

int main() 
{ 
    std::vector<std::string> time(1); 
    size_t d = 0; 

    std::cout << "What would you like to have inside of that?" << std::endl; 
    std::cout << "Please enter a sentence: "; 
    std::getline(std::cin, time[d]); 

    std::cout << "Is this what you wrote?" << std::endl; 
    std::cout << "[" << time[d] << "]" << std::endl; 

    return 0; 
} 
0

而不是使用cin採取輸入time[d],請嘗試使用getline。您可以修改代碼如下 -

cout << "Please enter a sentence: "; 
std::getline(std::cin, time[d], delim); 

現在只需要time[d]作爲字符串直到劃界字符delim被發現。定界字符可以類似於\t,\n等。

如果您未指定分隔字符,則需要使用\n作爲默認分隔符。