Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 通过c++;_C++_C_String_Input - Fatal编程技术网

C++ 通过c++;

C++ 通过c++;,c++,c,string,input,C++,C,String,Input,在C语言中,假设我需要从字符串中获取输入 int num,cost; char *name[10]; printf("Enter your inputs [quantity item_of_name at cost]"); scanf("%d%*c%s%*c%*s%*c%d",&num,name[0],&cost); printf("quantity of item: %d",num); printf("the cost of item is: %d",cost)

在C语言中,假设我需要从字符串中获取输入

 int num,cost;
 char *name[10];
 printf("Enter your  inputs [quantity item_of_name at cost]");
 scanf("%d%*c%s%*c%*s%*c%d",&num,name[0],&cost);

 printf("quantity of item: %d",num);
 printf("the cost of item is: %d",cost);
 printf("the name of item is: %d",name[0]);
输入

12点一本书

输出

项目数量为:1

项目成本为:12

项目名称为:图书

现在我想在C++中做同样的事情。我不知道该怎么接近。gets()返回整个字符串。是否有我遗漏的特定函数?请帮助。

int num,成本;
int num,cost;
std::string name;
std::cout << "Enter your  inputs [quantity item_of_name at cost]: ";
if (std::cin >> num >> name >> cost)
{ } else 
{ /* error */ }
std::字符串名; 标准::cout>num>>名称>>成本) {}其他 {/*错误*/}

<>你希望在C++中添加错误处理< /p> < p>你应该使用<代码> CIN <代码> > <代码> cOUT>代码>和<代码>字符串>代码>标准库。

可以使用IoString的CIN。
int num,cost;
 char *name[10];
 std::cout <<"Enter your quantity"<<std::endl;
 std::cin>> num;
 std::cout<<" Enter the cost"<<std::endl;
 std::cin>>cost;
 std::cout<<"Enter the name"<<std::endl;

 std::cout<<"The quantity of the item is: "<<num<<" costing: "<<cost<<" for "<<name[0]<<std::endl;
int num,成本;
字符*名称[10];
STD:C++中的CUT< P>,通过<代码> > >代码>运算符,与用户提供读写通信。
您的代码转换为

int num,cost;
std::string name;

std::cout << "Enter your  inputs [quantity item_of_name at cost]" << std::flush;
std::cin >> num >> name;
std::cin >> at; // skip the at word
std::cin >> cost;

std::cout << "quantity of item: " << num << std::endl;
std::cout << "the cost of item is: " << cost << std::endl;
std::cout << "the name of item is: " << name << std::endl;
int num,成本;
std::字符串名;
std::cout num>>名称;
std::cin>>at;//跳过这个词
标准:cin>>成本;

你的问题有点困惑,因为你的C代码不是从字符串中获取输入,而是从标准输入中获取输入。你到底想干什么?此外,你使用的C函数也将在C++中工作。无论如何,他的C代码都被破解了:他把未初始化的指针作为第三个参数传递给<代码> SCANF。即使它被初始化:用户也可以很容易地用足够长的名称使程序崩溃。在C语言中,在
scanf
中使用
“%s”
时,必须指定最大长度。我所要做的就是使用格式说明符将适当的输入(在字符串中)存储到相应的变量中。现在我从未见过C++中使用C函数(或者C中使用什么)。(我不是说你不能。我基本上还是初学者)。基本上我试图把问题从C转换成C++。@ PEPS,输入的C++方式是由SEHE给出的,但是C的方式也适用。是的,但是我想这是不用说的。OP看起来像新手(一般来说,他看起来像是受过教育的人,C++只是“C类”。所以我认为这是一个重要的评论。我的假设是,他使用(很好地知道)一系列的字符指针,他知道错误处理,但是在我的镇静中没有停下来考虑这可能是一个家庭作业的问题,并且只是提供了代码。你的代码产生了与提问者相同的未定义行为。最好将
可以
替换为
应该
并告诉他/她错误。