2014-01-27 21 views
1

我很好奇我是否可以在Mac終端中編寫C程序。看起來是的,但是當我開始嘗試使用字符串時,編譯時出現錯誤。在Mac終端中編寫一個基本的「C」程序

#include <stdio.h> 
#include <string.h> 

int main(void) { 
     string s = "chris"; 
     printf("hello %s \n", s); 
} 

當我編譯這個我得到一個消息說use of undeclared identifier 'string' - string s = "chris";

我已經試圖加入using namespace std;,但說using是不確定的。我已經嘗試#include <string>#include <string.h>

任何想法將不勝感激。

+4

C中沒有「'string」「;這聽起來像是混合了C和C++概念。 –

+1

而在C++中,你可以使用'#include '來使用'std :: string'。但最重要的是,不要試圖用隨機的東西編寫C或C++,先讓自己先讀一本書。 –

+0

使用C++編譯器 –

回答

2

string是一個標準的C++庫類。改爲使用const char *

#include <stdio.h> 

int main(int argc, const char **argv) { 
     const char *s = "chris"; 
     printf("hello %s \n", s); 
     return 0; 
} 
+0

嗯,好的。我跟隨在線課程,他們說他們正在使用「C」,他們正在使用字符串,也許我的線路在某處。 – Chris

+1

@Chris除非你在'main()'之前執行'typedef const char * string;',那麼我認爲你的電線已經穿過了。如果他們使用的是C++,那麼'printf()'中的'%s'將會中斷,你通常使用'std :: cout'而不是C++。 – trojanfoe

+0

即使你使用typedef,string也是C中的一個保留標識符,所以它仍然是錯誤的。 –

相關問題