开发者

Can getline() be used to get a char array from a fstream

开发者 https://www.devze.com 2022-12-15 06:50 出处:网络
I want to add a new (fstream) function in a program that already uses char arrays to process strings.

I want to add a new (fstream) function in a program that already uses char arrays to process strings. The problem is that the below code yields strings, and the only way i can think of getting this to work would be to have an intermediary function that would copy the strin开发者_如何学JAVAgs, char by char, into a new char array, pass these on to the functions in the program, get back the results and then copy the results char by char back into the string.

Surely (hopefully) there must be a better way?

Thanks!

void translateStream(ifstream &input, ostream& cout) {   
  string inputStr;
  string translated;

  getline(input, inputStr, ' ');

  while (!input.eof()) {
    translateWord(inputStr, translated);
    cout << translated;
    getline(input, inputStr, ' ');
  }

    cout << inputStr;

the translateWord func:

void translateWord(char orig[], char pig[]) {
  bool dropCap = false;
  int len = strlen(orig)-1;
  int firstVowel = findFirstVowel(orig);
  char tempStr[len];

  strcpy(pig, orig);


  if (isdigit(orig[0])) return;


  //remember if dropped cap
  if (isupper(orig[0])) dropCap = true;        

  if (firstVowel == -1) {
    strcat(pig, "ay");
    //    return;
  }

  if (isVowel(orig[0], 0, len)) {
    strcat(pig, "way");
    //    return;
  } else {

    splitString(pig,tempStr,firstVowel);

    strcat(tempStr, pig);
    strcat(tempStr, "ay");

    strcpy(pig,tempStr);
  }


  if (dropCap) {
    pig[0] = toupper(pig[0]);
  }

}


You can pass a string as the first parameter to translateWord by making the first parameter a const char *. Then you call the function with inputStr.c_str() as the first parameter. Do deal with the second (output) parameter though, you need to either completely re-write translateWord to use std::string (the best solution, IMHO), or pass a suitably sized array of char as the second parameter.

Also, what you have posted is not actually C++ - for example:

char tempStr[len];

is not supported by C++ - it is an extension of g++, taken from C99.


You can use the member function ifstream::getline. It takes a char* buffer as the first parameter, and a size argument as the second.

0

精彩评论

暂无评论...
验证码 换一张
取 消