2016-10-12 51 views
0

我正在做一個學校任務,我必須從一個文件讀取動態分配的結構數組。對於所有陣列,我只能使用C風格字符串和指針數組語法(即*(pointer + x))。我已經到了一個點,我試圖將所有內容加載到它們的位置,但是當我這樣做時,我的變量的末尾總是有垃圾。如何解決這個問題?我不斷收到一串額外的字符在我的C字符串結尾

#include <iostream> 
#include <fstream> 
#include <cstdlib> 

using namespace std; 

struct Pieces 
{ 
    char* word; 
    int jump; 
}; 

void reset(char*, int); 
int strLen(char*); 
void createArr(char*, char*); 

int main() 
{ 
    Pieces* cip; 
    char* temp; 
    ifstream input; 
    int numWords, numKeys; 

    temp = new char[20]; 
    input.open("Project4Data.txt"); 
    input >> numWords; 
    input >> numKeys; 
    cip = new Pieces[numWords]; 
    for(int x = 0; x < numWords; x++) 
    { 
     int tempSize; 
     reset(temp, 20); 
     input >> temp; 
     tempSize = strLen(temp); 
     //cout << temp << " "; 
     (cip + x)->word = new char[tempSize]; 
     //cout << tempSize; 
     reset((cip + x)->word, tempSize); 
     createArr((cip + x)->word, temp); 
     input >> (cip + x)->jump; 
     //cout << (cip + x)->word<< << endl; 
    } 
    input.close(); 

    //cout << (cip + 2)->word; 
    delete[] cip; 
    return 0; 
} 

int strLen(char* word) 
{ 
    int s = 0; 
    //cout << word; 
    for(int x = 0; *(word + x) != '\0'; x++) 
     s++; 
    return s; 
} 

void reset(char* arr, int size) 
{ 
    for(int x = 0; x < size; x++) 
     *(arr + x) = '\0'; 
} 

void createArr(char* a, char* b) 
{ 
    reset(a, strLen(b)); 
    for(int x = 0; x < strLen(b); x++) 
     *(a + x) = *(b + x); 
     cout << a; 
} 

當我發送(CIP + X) - >字溫度createArr使得溫度的有效內容可以被複制到(CIP + X) - >單詞,*(cip + x) - >單詞最後總是會出現大量垃圾,儘管我將其中的所有內容都設置爲null,並且僅使用了第一對夫婦指數。我該如何解決?

數據文件上有這樣的信息:

的Java 2版Linux 3恐懼0池2做0紅1個鎖。 1 I 0隨機2臺電腦,0不是0 0開2車! 2 C,0缺0 0狗1綠2 C++ 0瓶2錯,2他們。 0

+1

在'createArr'去與'X <= strlen的(b)中'複製0炭終止子。或者在'for'循環的末尾插入'*(a + strLen(b))= 0'。當然,確保'a'具有足夠的空間,並且更好地使用局部變量來存儲'b'的長度,而不是每次需要它的長度時迭代它。 –

回答

0

C樣式字符串以null結尾,所以最終可打印字符之後的字符需要等於0或'\ 0'。 您可以在循環後手動設置,或者按照Adrian的說法進行設置,並用小於/等於的值替換小於。

void createArr(char* a, char* b) 
{ 
    reset(a, strLen(b)); 
    for(int x = 0; x < strLen(b); x++) 
     *(a + x) = *(b + x); 
     *(a + x) = *(b + x); 
     cout << a; 
} 

或(可能更整潔)

void createArr(char* a, char* b) 
    { 
     reset(a, strLen(b)); 
     for(int x = 0; x <= strLen(b); x++) 
      *(a + x) = *(b + x); 
      cout << a; 
    } 
相關問題