【发布时间】:2020-01-17 08:42:45
【问题描述】:
我正在尝试解决这个练习,但我找不到我的错误。这个练习要求我们操作一个任意大小的正整数。为此,我们通过首先存储低权重的数字来选择数字的简单链表形式的表示。
我被要求完成lecture_nombre 和display_nombre 函数......
不过问题出在main,程序没有进入if( n != nullptr )循环。
这是我的代码:
#include <iostream>
#include <cctype>
#include <fstream>
using namespace std;
struct Chiffre {
unsigned int chiffre_; /**< single number between 0 et 9 */
Chiffre * suivant_; /**< pointer towards the next number with a heavier weight (for example 2 for 25 ou nullptr */
};
typedef Chiffre* Nombre;
void insertNode(unsigned int n, Nombre head, Nombre tail);
Nombre lecture_nombre( std::istream & in );
void display_nombre( Nombre n, std::ostream & out );
// The main is given by the teacher
int main(){
while( true ) {
Nombre n = lecture_nombre( std::cin );
if( n != nullptr ) {
std::cout << "lu : ";
display_nombre( n, std::cout );
std::cout << "\n";
//detruit_nombre( n );
}
else break;
}
return 0;
}
// d is a single digit number and I have to add it into the chained list and return the results
Nombre lecture_nombre( std::istream & in )
{
*//Nombre res = nullptr;
Nombre head = nullptr;
Nombre tail = nullptr;
while( in.good() ) {
char c = in.get();
if( std::isdigit( c )) {
unsigned int d = c - '0';
// my code starts here :
insertNode(d,head,tail);
}
else break;
}
return head;
}
// my code starts here
void insertNode(unsigned int n, Nombre head, Nombre tail){
struct Chiffre *newChiffre = new Chiffre;
newChiffre->chiffre_ = n;
newChiffre->suivant_ = nullptr;
cout << "Insert Node :" << newChiffre->chiffre_ << endl;
if (head==nullptr){
head = newChiffre;
tail = newChiffre;
}else{
tail->suivant_ = newChiffre;
tail = tail->suivant_;
}
}
void display_number( Nombre n, std::ostream & out ){
if(n==nullptr){
cout << n << endl;
}else{
cout << n->chiffre_ <<endl;
display_number(n->suivant_,out);
}
}
我验证了节点已创建但我无法显示数字,程序将 n 作为nullptr 所以它从未进入if( n != nullptr ) 循环...
【问题讨论】:
-
有问题的代码在哪里?您是否可以尝试将代码最小化为仅复制问题所需的部分(即创建一个minimal reproducible example 向我们展示)?还要确保您向我们展示的代码仅复制您询问的问题并且不包含任何不相关的错误(您显示的代码确实如此),并且最好不需要任何外部数据(如文件)来工作(硬代码数据(如果需要)。
-
在不相关的注释上,请阅读Why is iostream::eof inside a loop condition (i.e.
while (!stream.eof())) considered wrong? 做while (in.good())一样糟糕。 -
顺便说一句,我认为您应该阅读教科书中关于references 以及如何通过引用传递参数 的章节。也许甚至退后一步,阅读一般的论点传递。
-
主要是我不明白为什么n总是等于nullptr...
-
@hyde typedef是老师给的,要求我们完成lecture_nombre和display_nombre函数...
标签: c++ list pointers reference singly-linked-list