2015-01-10 140 views
0

我對代碼的問題在這裏,我與一個結構這個簡單的代碼面臨的一個錯誤,如果你在錯誤聲明「表達編譯那麼編譯器狀態必須是可修改的左值「。 我在這段代碼中基本上想要的是用一個struct數組來分配一個名字。 所以當寫入x [1] .identification =「Id」; ,那麼編譯器會給出錯誤。 我很困擾這個問題一段時間。C++錯誤「表達必須修改的左值」

有人可以解決這個問題嗎?!

謝謝


下面是代碼:

#include "stdafx.h" 
#include<iostream> 
#include<cstring> 
#include<cstdlib> 
#include<iomanip> 
#include<windows.h> 
//#include <ctime> 
//#include <dos.h> 
#include<dos.h> 
#include<conio.h> 
#include<cstdio> 
#define max 20 
using namespace std; 


struct person 
{ 

char identification[20]; 
long int code; 
char group [20]; 
int experience; 
int age; 

}; 


int main() 
{ 

person x[10]; 

x[1].identification = "Id"; // this is where the error is being shown 

system("cls"); 
return 0; 

} 
+0

它嘗試將常量字符指針的地址分配給常量地址。 'x [1] .identification'是一個數組,不是一個指針,所以你不能把地址放在裏面。如果您必須使用c字符串,請使用'strcpy'來複制它。 – SHR

回答

1

您試圖分配const char*char陣列。這是沒有意義的。使用std::string代替:

struct person { 
    std::string identification; 
    long int code; 
    std::string group; 
    int experience; 
    int age; 
}; 

您可能還需要創建一個構造函數,否則codeexperienceage是不確定的。你應該在施工時要求他們。

+0

這並不解決OP的實際問題,即使它是一種可能的解決方法... – nbro

+1

@Rinzler它怎麼不能完全解決OP的問題? – Shoe

+1

最初的錯誤和問題是:'表達式必須是可修改的左值'而不是如何從char數組傳遞到'std :: string' – nbro

相關問題