2010-06-08 196 views
0
#include <iostream> 
using namespace std; 

int main() { 

    short int enterVal; 
    cout << "enter a number to say: " << endl; 
    cin >> enterVal; 
    system("say "%d"") << enterVal; 

    return 0; 
} 

是我目前正在尝试。我希望用户输入一个数字,而system()函数基本上是这样说的。上面的代码有一个错误,说“'d'没有在这个范围内声明”。提前致谢。输入系统()功能(Mac)

回答

3

您必须手动格式化字符串。

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

int main() 
{ 
    short int enterVal; 
    cin >> enterVal; 

    stringstream ss; 
    ss << "say \"" << enterval << "\""; 
    system(ss.str().c_str()); 
} 
+0

谢谢,很好! – Alex 2010-06-08 21:42:46

0

您必须转义引号并格式化字符串。这样做的另一种方法是:

#include <iostream> 
#include <stdio.h> 
using namespace std; 

int main() { 
    short int enterVal; 
    char command[128]; 
    cout << "enter a number to say: " << endl; 
    cin >> enterVal; 
    snprintf((char *)&command, 128, "say \"%d\"", enterVal); 
    system(command); 
    return 0; 
} 

你也应该知道,你应该编程避免使用()调用,因为这会使你的程序存在安全漏洞。

如果你只是乱搞,不介意然后通过各种手段继续;)

+0

呀,这个程序只是为了好玩。 :) – Alex 2010-06-08 21:55:47

0

你可以使用这样的事情:

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

int main() { 

    short int enterVal; 
    cout << "enter a number to say: " << endl; 
    cin >> enterVal; 
    ostringstream buff; 
    buff << "say " << enterVal; 
    system(buff.str().c_str()); 

    return 0; 
}