2017-08-02 38 views
0

我正在嘗試讀取一個字符串,直到達到','字符並將已讀取的字符存儲到新字符串中。讀取字符串直到標誌(C++)

例如「5,6」

// Initialise variables. 
string coorPair, xCoor, yCoor 

// Ask to enter coordinates. 
cout << "Input coordinates: "; 

// Store coordinates. 
cin >> coorPair 

// Break coordinates into x and y variables and convert to integers. 
// ? 

我還需要將y值存儲在一個單獨的變量中。

在C++中執行此操作的最佳方法是什麼?

此外,是驗證輸入轉換爲整數並測試值範圍的最佳方法嗎?

+0

的可能的複製[最優雅的方式來分割字符串?(https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string) – vasek

+0

的可能的複製https://stackoverflow.com/questions/1894886/parsing-a-comma-delimited-stdstring – cup

回答

1

如果在字符串只有一個逗號分隔符,你可以找到在哪裏逗號第一次出現在輸入和與發現的位置串輸入。

嘗試以下操作:

std::size_t pos = coorPair.find_first_of(","); //Find position of ',' 
xCoor = coorPair.substr(0, pos); //Substring x position string 
yCoor = coorPair.substr(pos + 1); //Substring y position string 
int xCoorInt = std::stoi(xCoor); //Convert x pos string to int 
int yCoorInt = std::stoi(yCoor); //Convert y pos string to int 
+0

謝謝,這工作得很好。我只是不得不交換pos.substr與coorPair.substr – user6336941

+0

@ user6336941糟糕,我的壞。 – Gear

0

您可以通過分隔符指定你和解析字符串

std::string delimiter = ","; 

size_t pos = 0; 
std::string token; 
while ((pos = coorPair.find(delimiter)) != std::string::npos) { 
    token = coorPair.substr(0, pos); 
    std::cout << token << std::endl; 
    coorPair.erase(0, pos + delimiter.length()); 
} 

std::cout << coorPair << endl; 

在{5,6}的最後一個令牌例如{6}將在coorPair做到這一點。

另一種方法是使用std::getline在評論中指出:

std::string token; 
while (std::getline(coorPair, token, ',')) 
{ 
    std::cout << token << std::endl; 
} 
+1

使用'std :: getline()'以'',''作爲分隔符會更容易。 –

+0

可以,是的,我認爲OP對'解析'感興趣。 –

+1

它仍然是解析,只是讓STL幫助,例如:'std :: string token; while(std :: getline(coorPair,token,',')){std :: cout << token << std :: endl; }' –

1

要做到這一點,只是讓operator>>做所有的工作對你來說最簡單的方法:

int xCoor, yCoor; 
char ch; 

cout << "Input coordinates: "; 

if (cin >> xCoor >> ch >> yCoor) 
{ 
    // use coordinates as needed ... 
} 
else 
{ 
    // bad input... 
} 
0

http://www.cplusplus.com/reference/string/string/getline/

我會建議使用函數getline( )。

下面是我如何使用它的一個小例子。它接受來自流的輸入,因此您可以使用ifstream作爲輸入,或者執行下面的操作並將字符串轉換爲流。

// input data 
std::string data("4,5,6,7,8,9"); 

// convert string "data" to a stream 
std::istringstream d(data); 

// output string of getline() 
std::string val; 

std::string x; 
std::string y; 
bool isX = true; 

char delim = ','; 

// this will read everything up to delim 
while (getline(d, val, delim)) { 
    if (isX) { 
     x = val; 
    } 
    else { 
     y = val; 
    } 
    // alternate between assigning to X and assigning to Y 
    isX = !isX; 
}