ChaosSpring 2022-04-19 11:23 采纳率: 100%
浏览 34
已结题

c++getline输入问题


#include <cstring>
#include <string>
#include <iostream>

#define max 1000
using namespace std;

struct block // the structure of block
{
    int index;       // the index of the block
    string text;   // the text that the user want to store
    string p_hash; // previous hash value
    string hash;   // hash value
    block *next;   // linked list
};

struct blockchain // the structure of blockchain
{
    struct block block_array[max]; // define a maximum of 1000 blocks in the blockchain
    int max_size;
};

string hash_function(string s) // the hash function
{
    string input(s);
    SHA1 checksum;
    checksum.update(input);
    char hash[41];
    strcpy(hash, checksum.final().c_str());
    return hash;
}

void add_block(blockchain *block) // add block
{
    if (block->max_size == max)
    {
        cout << "Input failure." << endl;
        return;
    }
    else
    {
        cout << "Enter the index of blocks you want to add: ";
        int add_index = 0;
        cin >> add_index; // confirm the index of the added block
        if (add_index > 0)
        {
            int new_size;
            new_size = block->max_size + add_index;
            for (int i = block->max_size; i < new_size; i++)
            {
                string text;
                string p_hash;
                string hash;
                cout << endl;
                cout << "\tPlease enter the imformation of block No." << i + 1 << endl;
                cout << "\tPlease enter the text: ";
                text = "\n";
                getline(cin, text);

                block->block_array[i].index = i + 1;
                block->block_array[i].text = text;
                block->block_array[i].p_hash = p_hash;
                block->block_array[i].hash = hash;

                p_hash = hash;
                block->max_size++;
            }
        }
    }
}

int main()
{
    blockchain block;
    block.max_size = 0;
    add_block(&block);
}

当我在add——block中添加时,使用getline会跳过i = 0而直接到i = 1。即在i = 0时无法输入,想问原因。

img

  • 写回答

1条回答 默认 最新

  • qfl_sdu 2022-04-19 11:32
    关注

    在getline函数之前清空一下输入缓存,添加如下代码:

    //添加下面两句话,清空输入缓存
    cin.clear();
    cin.sync();
    //原来的代码...
    getline(cin, text);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月27日
  • 已采纳回答 4月19日
  • 创建了问题 4月19日

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。