【发布时间】:2016-03-03 20:25:10
【问题描述】:
我写了这个函数来从 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) 中调用此函数并输入 blabla 时,它会将“blabla”读入缓冲区。 (我通过 cout-for-loop 进行了检查)
当我想读取另一个数组(用于比较)并执行完全相同的操作 returncode = read(second, MAX) 时,它只会读取“labla”,而 second[0] 仍然为空。
我的错在哪里?随意询问其余的代码,但我认为问题出在这段代码 sn-p 之内。
提前谢谢你!
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:添加字符串比较忽略空格函数
由于错误似乎不在读取函数中,这是使用第一和第二两个输入缓冲区的文件:
#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
【问题讨论】:
-
您能否尝试创建一个Minimal, Complete, and Verifiable Example,包括一个简单的
main函数,该函数调用您显示的函数。还包括程序的实际(和预期)输出。 -
我编辑我的帖子。请一秒钟。
-
您是否为第二次通话输入了一些内容?
-
首先你的循环是错误的,它不应该使用
i < size作为条件,而是first[i] != '\0' -
在修复一个小问题后没有使用 GCC 或 MSVC 进行复制(这可能表明发布的代码不是 OP 实际运行的代码?)。