2014-12-07 90 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