2014-12-07 59 views
0

基本上我的代碼不會打印令牌。它只是打印空白。我究竟做錯了什麼? 我在這個問題上諮詢了許多其他指南,我似乎無法理解我做錯了什麼。打印所有空白(字面上不打印令牌)

謝謝。

#define _CRT_SECURE_NO_WARNINGS 
#include <iostream> 
#include <stack> 
#include <stdexcept> 
#include <string> 
#include <stdlib.h> 
#include <cstring> 
using namespace std; 

int main() { 
    stack<double> s; 
    string str = ""; 
    getline(cin, str); 
    char *cstr = new char [str.length()+1]; 
    strcpy(cstr, str.c_str()); 
    char* strp = strtok(cstr, " "); 
    while (strp != 0){ 
     double n = strtod(cstr, &strp); 
     s.push(n); 
     cout << strp << endl; 
     strp = strtok(0," "); 
     } 
    return 0; 
} 
+0

你提供什麼輸入? – 2014-12-07 09:36:37

+1

'double n = strtod(cstr,&strp);'錯了,應該是'double n = strtod(strp,&other_pointer);' – BLUEPIXY 2014-12-07 09:37:40

+0

@退休忍者2 3 + //輸出是3個空格 – 2014-12-07 09:38:18

回答

0

此代碼的工作對我來說:

int main() 
{ 
    stack<double> s; 
    string str = ""; 
    getline(cin, str); 
    char *cstr = new char [str.length()+1]; 
    strcpy(cstr, str.c_str()); 
    char* strp = strtok(cstr, " "); 
    while (strp != NULL) 
    { 
     double n = strtod(strp, NULL); 
     s.push(n); 
     cout << n << endl; 
     strp = strtok(NULL, " "); 
    } 

    return 0; 
} 

但地獄,這確實是C和C++中不好受組合。你應該擺脫那些strcpy,strtok和strod函數。改用istringstream。

+0

是的,我的教授在他的一些示例程序(用於C++課程)中使用了strtok,所以我想嘗試這樣做,因爲我根本沒有太多的C語言知識。對於istringstream路由,它可能會更直接。 – 2014-12-07 10:08:42