2011-04-09 4 views
1

프로그래밍에 약간 익숙해서 문제를 해결하지 못했지만 작업을 완료하려고 시도했습니다. 여러 가지 방법.다른 배열에서 수정 된 배열의 가비지 값을 함수에서 계속 얻습니다.

문제는 내가 단어 배열을 가져와 배열에서 구두점을 제거하고 새 단어를 별도의 배열에 배치하려고한다는 것입니다. 나는이 작업을 시도했지만 새 배열을 출력 할 때 가비지 값을 계속 유지합니다.

코드 읽

norm(sepwords1,sepwords2,numwords);  <- where I called it in main 

void norm(string words[], string wordz[],int count)  
{ 

     int i; 
     int x; 

     string newstring=""; 
     char current; 


    for(i=0; i<count; i++) 
     { 
     for(x=0; x<words[i].length();x++) 
     {   
      current= words[i].at(x); 
       if(ispunct(current)==0) 
       { 
       newstring += current; 
       } 

     }   
       wordz[i]= newstring; 
     } 

} 

전체의 주요 기능은 다음과

int main (int argc, char* argv[]) 
{ 



int count = argc; 
int i; 
string filename[count]; 
ifstream infile; 
string fromfile[1000]; 
int numdata; 
int pass; 
char current; 
int sum; 
string masterstring=""; 
int x; 
string sepwords[2000]; 
int sum1; 
string temp=""; 
int start; 
int fin; 
string newstring=""; 
string newfile[1000]; 
int place; 
int numwords; 
string sepwords1[2000]; 
string newmaster=""; 
int j=0; 
string currentz; 
string highmark; 
int index[2000]; 
string sepwords2[2000]; 
int counta=0; 

for(i=0; i < count-1; i++) 
{ 
filename[i] = argv[i+1]; 
} 

for(i=0; i < count-1; i++) 
    { 
    infile.open(filename[i].c_str()); 

    numdata=0; 

    while(!infile.eof()) 
    { 

    getline(infile, fromfile[numdata], '\n'); 
    numdata++; 

    } 





    for(i=0; i<numdata; i++) 
    { 
    cout<<fromfile[i]<<endl; 
    masterstring += fromfile[i] + " ";          //NUMBER ONE 
    } 



    numwords = split(masterstring, sepwords); 
    cout<<numwords<<endl;              //NUMBER TWO 


    } 

    for(i=0;i<numwords;i++) 
    { 
     newstring = toupper(sepwords[i].at(0));   
     newstring += sepwords[i].substr(1); 
     sepwords1[i] = newstring; 
     newstring=""; 
    } 

    for(i=0;i<numwords;i++) 
    { 


    newmaster += sepwords1[i] + " "; 
     j++; 
      if(j > 10) 
      { 
      newmaster+= '\n'; 
      j=0; 
      } 

    } 
    cout<<newmaster<<endl;            //NUMBER THREE 



    norm(sepwords1,sepwords2,numwords); 

     for(i=0;i<numwords;i++) 
    { 
    cout<<sepwords2<<endl; 
    } 

return 0; 
} 
+0

'norm'으로 전달한 원래 배열을 어떻게 선언합니까? 이 문자열 목록이 변수가 될 수 있다고 가정 할 때 배열을 사용하는 이유가'std :: vector'가 아닌가요? – birryree

+0

외부 루프의 반복마다 newstring = ""을 원한다고 생각합니다. – jfs

+0

코드를 구현하는 방법을 알지 못해 벡터를 사용하지 않았습니다. P – Sam

답변

0

가제트 출력의 의미를 잘 모르시겠습니까?

나는이 (g ++ 4.4.5)로 함수를 호출하는 경우

#include <string> 
#include <iostream> 
using namespace std; 
int 
main (int ac, char **av) 
{ 
    int numwords = 3; 
    string sepwords1[] = {"one,", "two", "three"}; 
    string sepwords2[numwords]; 
    norm(sepwords1,sepwords2,numwords); 
    for(size_t i=0;i<numwords;++i){ 
    std::cout<<"sepwords2["<<i<<"] = "<<sepwords2[i]<<std::endl; 
    } 

} 

는 I 출력

sepwords2[0] = one 
sepwords2[1] = onetwo 
sepwords2[2] = onetwothree 

이 당신이 원하는 아닌가요거야? 당신이 concatination을 원하지 않는 경우에, 당신이를 NewWord 변수를 재설정해야

,

wordz[i]= newstring; //this is in your norm function 
    newstring="";   //this is the line I added. 

다음 출력이

sepwords2[0] = one 
sepwords2[1] = two 
sepwords2[2] = three 
+0

다소 그런 것 같습니다. 각 단어에서 구두점을 제거하고 보조 배열에 저장하면됩니다. 내가 제공 한 코드를 사용하면 sepwords2 []에서 cout을하면 모든 요소에 대해 "0xffbf5828"이됩니다. 내가 놓친 게 있니? 또한, 나는 당신이 쉼표를 제거하기 위해 무엇을했는지 이해하지 못한다. – Sam

+0

@sam 문자열에 연결하기 전에 "if (ispunct (current) == 0)"체크를 가지고 있기 때문에 필자가 제거되었다 - 나는 당신의 함수를 변경하지 않았다. 내가 말했던 추가 라인을 제외하고는. – Tom

+0

아 맞습니다. 그렇습니다. ispunct 함수가 무엇을했는지 알았습니다. 다른 방법을했을 수도 있습니다. 그러나 나는 당신의 제안을 덧붙여서 나는 그것이 왜 합리적인지 알지만, 나는 계속 0xffbf5828 값을 얻는다. 코드의 다른 부분에있을 수 있습니까? 그 시점까지는 모든 일이 끝났고 메인 메뉴에서는 "sepwords1 [2000]"및 "sepwords2 [2000]" – Sam

0

어레이 크기 배열 고정되어있다. "배열"에서 요소를 추가하고 제거해야하는 경우 가변 크기의 시퀀스 인 목록이나 벡터를 사용해야합니다.

3
귀하의 코드가 작동해야

,하지만 문제의 아마 거기 귀하의 배열 및 두 가지를 사용해야한다는 사실과 같은 주요 기능, 그래서 내가이 동작을 볼 하나의 이유는 귀하의 배열 크기가 서로 일치하지 않을 수 있습니다, 그리고 하나는 원래 문자열을 저장하는 것보다 큽니다 하나는 복사하고 있습니다. 약간의 비틀기로, 대부분 코드의

#include <string> 
#include <iostream> 

int main() { 
    const int SIZE = 5; 
    string oldArray[SIZE] = {"He,llo", "Wor,ld", "H,ow", "Ar,e.", "Y,O,U"}; 
    string newArray[SIZE]; 

    for (int i = 0; i < 5; ++i) { 
     // Moved this into the loop for ease, otherwise your 
     // original code would have kept appending to this 
     // newString variable unless you cleared it later 
     std::string newString = ""; 
     for (int x = 0; x < oldArray[i].length(); ++x) { 
      char current = oldArray[i].at(x); 
      if (ispunct(current) == 0) 
      { 
       newString += current; 
      } 
     } 
     newArray[i] = newString; 
    } 

    for (int i = 0; i < 5; ++i) { 
     std::cout << newArray[i] << '\n'; 
    } 
} 

주위 newString을 유지하지만 나중에 삭제하지 않고 연결 문제를 해결합니다.

std <algorithm> 항목을 사용하고 성장 및 크기 조정을 처리하는 <vector>을 사용하면이 문제를보다 간결하게 처리 할 수 ​​있습니다.

#include <iostream> 
#include <string> 
#include <algorithm> 
#include <vector> 

int main() { 
    std::vector<std::string> stringsToCopy; 
    stringsToCopy.push_back("Hel,lo,"); 
    stringsToCopy.push_back("th,ere."); 

    // Make a copy of the other vector, since it seems like you want to keep 
    // the original data. This will copy all the elements from the stringsToCopy 
    // vector. 
    std::vector<std::string> newStrings = stringsToCopy; 

    // simplicity, but you could use an iterator as well, which would be 
    // more verbose 
    for (int i = 0; i < newStrings.size(); ++i) { 
     // get a reference to the current string in the 
     // vector for convenience, so we can use a shorter 
     // name for it 
     std::string& s = newStrings[i]; 

     // because remove_if doesn't actually delete things from a 
     // container, we should also call the string's erase method 
     s.erase(std::remove_if(s.begin(), s.end(), ispunct), s.end()); 
    } 


    for (int i = 0; i < newStrings.size(); ++i) { 
     std::cout << newStrings[i] << '\n'; 
    } 
} 
+0

응답 해 주셔서 감사합니다. 지금 당장 실마리가 없으므로 벡터를보다 능숙하게 사용하는 방법을 배우려고 노력할 것입니다. 나는 두 개의 배열이 메인에서 2000이라는 크기로 선언 되었기 때문에 추가 할 것이라고 생각 했으므로 정확한 오류인지 확실하지 않습니다. (또는 어쩌면 나는 당신이 말한 것을 잘못 해석했다.) – Sam

+0

@Sam - 2000 요소는 괜찮다. - 'norm'에 전달하는 'count'는 무엇인가? 2000 또는 단어의 실제 문자열 수입니까? – birryree

+0

전체 주 기능을 게시했습니다. 개수는 원래 배열의 요소 수 여야합니다. 오, 배열에있는 단어의 수를 결정하는 데 사용하는 다른 함수가 있다는 것을 잊어 버렸지 만, 지금까지 문제가 해결되지 않았으므로이 문제는 의심 스럽습니다 – Sam

관련 문제