c++ - 当我按 enter 时程序不会继续

标签 c++

我以前从未遇到过这个问题。当我按 enter 接受 userInput 时,程序不执行。有什么理由吗?

#include <iostream>
using namespace std;

struct node{
  char data;
  struct node* left;
  struct node* right;
};


struct node* newNode(int idata){
  struct node* node = new struct node;

  node -> data = idata;
  node -> left = NULL;
  node -> right = NULL;

  return node;
};

void getUserInfo(string &userInput, int &lengthString){
  cout << "A string that contains a dot(.) will be invalid!" << endl;
  cout << "Enter a string ->";
  cin >> userInput;

  // getting the length of string
  lengthString = userInput.length();
}

void stringToChar(char *& charArray, int &lengthString){
  for(int i = 0; i < lengthString; i++){
    cin >> *(charArray+i);
  }
}

int main(){
  string userInput;
  int lengthString = 0;

  char * charArray;
  charArray = new char [lengthString];

  getUserInfo(userInput, lengthString);

  stringToChar(charArray, lengthString);

  /*struct node *root= newNode(9);
  root ->left = newNode(20);
  (*root).right = newNode(3);
  cout << root->right->data;
  */

  return 0;
}

最佳答案

您的问题是您的 stringToChar 方法中有另一个 cin。假设您想将字符串变成一个 char 数组,(根据您的参数和您声明的内容来判断,这就是您想要的)我更改了方法来实现它。

void stringToChar(char *& charArray, int &lengthString, string &userInput){
  for(int i = 0; i < lengthString; i++){
    charArray[i]=userInput[i];
  }
}

关于c++ - 当我按 enter 时程序不会继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49848057/

相关文章:

c++ - 在 OSX 中针对 OpenGL 和 Xm 编译 C/C++ 应用程序

c++ - c++访问模板变量的方法

c++ - 面向对象的方程式 API

c++ - 跟踪#include 依赖项的工具

c++ - std::array 可以在 constexpr 类中使用吗?

c++ - 初始化相互引用的对象

c++ - 使用运算符 float() 和带有静态成员的 float() const 的隐式转换

c++ - 如何为 python 编译 C/C++ 函数

c++ - 管道损坏,FIFO 文件

c++ - 在 Internet Explorer 上获取最小化和最大化事件