繁体   English   中英

为什么我的读取函数在第二次调用时会丢弃第一个字符?

[英]Why is my read function throwing away the first char when calling it a second time?

我编写了此函数以从cin读取char数组:

#include <iostream>
#include <stdlib.h>
#include <cstring>
#include "main.h"
int read (char* buffer, int size) {

//read from standart input (with whitespaces)
//cin >> buffer;
cin.get(buffer, size);
cin.ignore(1, '\n');
cout << "cin get buffer: " << buffer << endl;

//if not a correct input
if (!cin.good())
    return 0;

cout << "cin.good: " << cin.good() << endl;

//user wants to quit
if (!strcmp (buffer, "end"))
    return 0;

return 1;
}

当我在我的主returncode = read (first, MAX)第一次调用此函数时returncode = read (first, MAX)并输入blabla ,它将“ blabla”读入缓冲区。 (我通过cout-for-loop检查)

当我想读取另一个数组(用于比较),并做完全相同的事情returncode = read(second, MAX) ,它只读取“ labla”,其中second[0]保持为空。

我的错在哪里 随意询问其余的代码,但我认为错误在于此代码片段内。

先感谢您!

ps:我真的是c ++的新手,所以请耐心:) pps:这是大学考试,我们不允许使用字符串类。

编辑:一个简单的主要来测试以上

main.cpp中:

#include <iostream>
#include "main.h"
#define MAX 200
using namespace std;

int main () {
   char first [MAX] = {0};
   char second [MAX] = {0}; 

   cout<<"Please enter the first string to compare: "<<endl;
   returncode = read (first, MAX);
   cout<<"Please enter the second string to compare: "<<endl;
   returncode = read (second, MAX);

    switch (strcmp_ign_ws(first, second, MAX)) {
    case EQUAL:
       cout << "Strings are equal!" << endl;
       break;
    case SMALLER:
       cout << "String 1 is lexically smaller!" << endl;
       break;
    case BIGGER:
       cout << "String 1 ist lexically bigger!" << endl;
       break;
   }
}

和main.h:

#define EQUAL 0
#define SMALLER -1
#define BIGGER 1

int read (char*, int);
int strcmp_ign_ws (char*, char*, int);
int main ();

编辑2:添加字符串比较忽略空白功能

由于错误似乎没有出现在读取功能中,因此这是使用两个输入缓冲区first和second的文件:

#include <stdlib.h>
#include <stdio.h>
#include <cstring>
#include <iostream>
#include <ctype.h>
#include "main.h"

using namespace std;

char * rm_ws (char * buffer, const int size) {

    int i,j;
    char *output=buffer;
    for (i = 0, j = 0; i<size; i++,j++)
    {
        if (buffer[i]!=' ')
            output[j]=buffer[i];
        else
            j--;
    }
    output[j]=0;
    return output;

}


int strcmp_ign_ws (char * first, char * second, int size) {
    first = rm_ws(first, size);
    second = rm_ws(second, size);


    if (strcmp (first, second) == 0)
        return EQUAL;
    if (strcmp (first, second) < 0)
        return SMALLER;
    if (strcmp (first, second) > 0)
         return BIGGER;

    }
}

ps: rm_ws函数已经来自stackoverflow

您是在Windows还是基于Unix的系统上称呼它? 在Unix上没有这个问题,所以也许与Windows中结尾的不同行('\\ r \\ n'与'\\ n')有关,并且您使用了

cin.ignore(1, '\n');

不确定是否是问题所在,但只需尝试用简单的方法替换该行

cin.ignore();

经过数小时的调试,我终于得出答案:

在我的rm_ws函数中有一个小错误:

代替output[j] = 0它需要在return语句之前output[j-1] = 0

谢谢您的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM