如何解决带空格字符串读取到链表时被拆分的问题?
问题:读取带空格的字符串时链表插入异常
我将数据读取至链表中,每次在头部或尾部插入节点后都会显示所有节点。读取不含空格的名称时一切正常,但读取带空格的全名时程序无法正常工作——带空格的字符串会被拆分为两个不同的节点,通常分别插入至首尾。
相关代码
结构体定义:
struct node { char string_val[20]; struct node *next; };
创建节点的函数:
struct node *new_node() { struct node *new1=(struct node *)malloc(sizeof(struct node)); cin >> new1 -> string_val; new1 -> next=NULL; return new1; }
问题原因
cin >> 默认以**空白字符(空格、换行、制表符)**作为输入分隔符,读取时会自动跳过前导空白,然后读取直到遇到下一个空白字符为止。输入带空格的全名(比如John Doe)时,第一次cin >>只会读取John存入第一个节点,剩余的Doe会被下一次调用new_node()时的cin >>读取,从而生成第二个节点,导致拆分问题。
解决方案
方案1:使用cin.getline()读取整行输入
修改new_node()函数,注意先处理之前输入残留的换行符:
#include <limits> // 需要包含此头文件 struct node *new_node() { struct node *new1 = (struct node *)malloc(sizeof(struct node)); // 忽略之前输入留下的换行符,避免getline直接读取空行 cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 读取整行内容到字符数组,最多读取19个字符(留1个位置存结束符'\0') cin.getline(new1->string_val, sizeof(new1->string_val)); new1->next = NULL; return new1; }
方案2:改用C++的std::string(更推荐)
先修改结构体,用std::string替代字符数组:
#include <string> // 需要包含此头文件 struct node { std::string string_val; struct node *next; };
再修改创建节点的函数,用getline读取整行:
#include <limits> struct node *new_node() { // C++中更推荐使用new而非malloc struct node *new1 = new struct node; cin.ignore(numeric_limits<streamsize>::max(), '\n'); getline(cin, new1->string_val); new1->next = NULL; return new1; }
内容的提问来源于stack exchange,提问作者Josh Dazey
相关产品推荐
相关产品推荐

