Kaie"s Blog 2.0 beta!
Back to "Top"

My Secret Notebook
 Show "Table of Contents"
Contact Me
Subscribe to my Posts feed
Subscribe to my Comments feed
My Flickr
Back to "Top"
My Secret Notebook
 Show "Table of Contents"
Contact Me
Subscribe to my Posts feed
Subscribe to my Comments feed
My Flickr

Friday, April 28, 2006

[Programming] getline

  • Question:透過cin擷取輸入的字串,諸如:"What the fuck",然後分別以strtok切出這三個Token,再取strlen值為多少。然後我就直接宣告一個buffer,然後用cin或scanf來處理,都發現了一個問題,就是,那個buffer都只存到"What"就停了,後面的"the fuck"被略過了。以前沒注意到這問題,後來搞懂之後,普通的cin或scanf並無法解決遇到某些特殊字元的狀況。
  • Solution:透過 getline function 就可以輕易的解決問題

#include <iostream>
#include <cstring>
using namespace std;

int main(int argc , char** argv)
{
char str[100];
cin.getline(str,100,'\n');

cout<<"str = "<<str<<endl;
char *token = strtok(str, " ");
cout <<"Length("<<token<<") = "<< strlen(token) << endl;
while((token = strtok(NULL, " ")) != NULL )
{
cout <<"Length("<<token<<") = "<< strlen(token) << endl;
}
}