2017-09-01 226 views
-3

我无法让我的字符串声明被声明为变量。 int,double和char都改变字体颜色,但字符串不改变。无法声明字符串变量

#include <iostream> 
#include <string>  // Supports use of "string" data type 
using namespace std; 

int main() { 
    int userInt = 0; 
    double userDouble = 0.0; 
    char userChar = 0; 
    string userString = 0; // this string declaration is not being recognized 
+2

请检查[documentation](http://www.cplusplus.com/reference/string/string/string/) – hrust

+0

您不必初始化std :: string。只是'string userString;' – kangsu

+3

你得到了什么确切的编译器错误?你应该发布它,这样可以向你解释编译器在抱怨什么。 – PaulMcKenzie

回答

2

如果你想默认初始化std::string为空字符串,你不必做任何事情。这是默认完成的。

std::string x; 
std::string y = ""; 

两者相等。

x.compare(y) == 0 

您目前的初始化将不起作用。它会在运行时抛出异常。

std::string str = 0; 

请检查this example.


也是“字体颜色”并没有很多工作要做,它是一个变量或没有。这完全取决于您使用的IDE /编辑器。

  • 的IDE是不是上帝
  • 语法高亮可能无法正常工作的所有时间,如果一个变量被一个IDE突出或不
+0

我的问题与我将字符串初始化为什么没有任何关系。它与“字符串”不被识别为变量的事实有关。它没有改变颜色和运行时,我得到一个错误,说变量“userString”尚未宣布 –

+0

@RachelSugg不正确。如果你像这个'std :: string x = 0'初始化字符串,你会得到一个运行时错误。请重新检查我的回答关于您的“颜色”问题。此外,如果您有某个声明问题,您的程序将无法编译。 – Blacktempel

2

我刚刚意识到你没有使用在你的userString变量的值引号,而不是你应该输入字符串如下

string userString = "0"; // this string declaration is not being recognized 

我希望这能解决你的问题

+0

这个问题与我在字符串后键入的任何东西没有任何关系。只要我输入它,它应该改变显示被识别为变量的颜色。它并没有这样做。 –

+0

嘿,Rachel Sugg C++对于数据结构往往非常自以为是,例如 –

+0

请仔细阅读,但是字符串,字符都是用引号输入的,例如char ed =“a”;或字符串dd =“你好”;当你单独使用你的零(例如字符串userString = 0)时,C++编译器会压缩它,因为它需要用引号括起来的一组字符,因此可以使用布尔值,它使用1表示true,0表示false,例如布尔值t = 1;与布尔型t = true相同,也是布尔型f = 0;与布尔值f = false相同;或者你可以使用int,如果你只是想要一个数字,例如int n = 123; –

0

你根本忘了

  • C++不关心添加引号“”。它期望的是文本值,而不是数值。

    string userString = "0"; //is correct 
    string userString = 0; //is incorrect 
    

    另一个评论,只是让你知道正确的术语,上面的代码不只是一个声明。

    int myVal; //declaration of a variable of integer data type 
    int myVal = 10; //is called initialization (declaration and assignment) 
    

    编辑:我已经复制并粘贴您的代码到我的IDE,一个字符串的正确初始化,并能正常工作。我正在使用Codeblocks。