2013-03-07 31 views
0

我只是不明白爲什麼這個C++程序不想工作? 幫助!C/C++錯誤gdb atof(argv [1])需要更改爲idb才能正常工作

#include <iostream> 
#include <cstdlib> 
#include <cmath> 
using namespace std; 
int main (int argc, char* argv[]) 
{ 
    // convert the text argv[1] to double using atof: 
    double r = atof(argv[1]); 
    double s = sin(r); 
    cout << "Hello, World! sin(" << r << ")=" << s << endl; 
    // success 
    return 0; 
} 

報告:

"/usr/bin/gmake" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf 
gmake[1]: Entering directory /home/aleksandar/NetBeansProjects/CppApplication_2' 
"/usr/bin/gmake" -f nbproject/Makefile-Debug.mk dist/Debug/GNU_Compiler_Collection-Linux-x86/cppapplication_2 
gmake[2]: Entering directory /home/aleksandar/NetBeansProjects/CppApplication_2 
mkdir -p build/Debug/GNU_Compiler_Collection-Linux-x86 
rm -f build/Debug/GNU_Compiler_Collection-Linux-x86/main.o.d 
g++ -c -g -MMD -MP -MF build/Debug/GNU_Compiler_Collection-Linux-x86/main.o.d -o build/Debug/GNU_Compiler_Collection-Linux-x86/main.o main.cpp 
mkdir -p dist/Debug/GNU_Compiler_Collection-Linux-x86 
g++ -o dist/Debug/GNU_Compiler_Collection-Linux-x86/cppapplication_2 build/Debug/GNU_Compiler_Collection-Linux-x86/main.o 
gmake[2]: Leaving directory `/home/aleksandar/NetBeansProjects/CppApplication_2' 
gmake[1]: Leaving directory `/home/aleksandar/NetBeansProjects/CppApplication_2' 

BUILD SUCCESSFUL (total time: 613ms) 

RUN FAILED (exit value 1, total time: 78ms) 

/usr/local/netbeans-7.2.1/ide/bin/nativeexecution/dorun.sh: line 33: 7673 Segmentation fault sh "${SHFILE}" Press [Enter] to close the terminal ...

更新:上大學

我已經聯繫教授和解決方案,他告訴我的是:

如果我想在unix/linux環境下運行代碼,我需要aft呃編譯和鏈接用說:
c++ -o test.x test.cpp
然後運行代碼爲:
./test.x 0.4
而現在它的工作原理。
輸出是
Hello, World! sin(0.4)=0.389418
但有誰知道在編譯器中輸入0.4的控制檯的方式,而不是像這樣?

+1

當我的C++程序不想工作,我拔出我的鞭子。無論如何,我猜'argv [1]'不存在。 – chris 2013-03-07 23:43:28

+0

您確定您的程序是崩潰的程序,因爲您只共享了構建工具的輸出。此外,你的main()不會檢查它是否收到足夠的參數來獲得有效的argv [1]。更多信息將有所幫助。 – 2013-03-07 23:45:32

回答

2

argv[1]僅在argc >= 2有效。你應該檢查你的代碼。

argc僅當您使用命令行參數運行程序時纔會大於1

2

這是崩潰,因爲您不一定向程序發送命令行參數。 argv [0]始終是您正在運行的可執行文件的名稱,但不保證argv [1]存在或被允許取消引用。

如果您有興趣從用戶那裏獲得輸入,您應該使用位於標頭iostream中的std :: cin。你可以在你的程序

#include <iostream> 

,並閱讀來自用戶的浮點值,你可以不喜歡下面的頂部下面的代碼包括它(使用假設空間std):

float var; 
cout << "Enter a number: "; 
cin >> var; 

並且在代碼執行後,var將包含用戶輸入的浮點值。

+0

我已經聯繫了那所大學的教授,他告訴我的解決方案是:
「如果你在unix/linux環境下運行代碼,編譯並鏈接後說 'C++ -o test.x test.cpp' 你運行的代碼爲 './test.x 0.4'「 但我仍然不明白爲什麼它需要這樣? – Aleksa 2013-03-08 09:05:50

1

您沒有提供任何命令行參數,因此argv[1]會導致分段錯誤。

-1

!!!已解決!!!

該probem是:gdb中的錯誤我需要更改爲intel64/idb工作!

我已經竭盡所能不同的編譯器和運行這些程序(Netbeans的,Eclipse的 ,Qt Creator的.....)

當我改變了:GDB-> IDB

IT工作! !

錯誤報道: http://sourceware.org/bugzilla/show_bug.cgi?id=15257

+0

從您提供的信息來看,這在您的項目設置中看起來像是一個問題,而不是在'gdb'中。你是否在NetBeans中設置了項目的「命令行參數」? – 2013-03-08 21:31:13

相關問題