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

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

//添加下面两句话,清空输入缓存
cin.clear();
cin.sync();
//原来的代码...
getline(cin, text);