gpt4 book ai didi

c++ - 如何在将 double 作为输入后将整行作为字符串变量的输入?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:10:38 27 4
gpt4 key购买 nike

目标:用c++写一个程序

1.声明变量:一个是double类型,一个是String类型。

2.在新行上将 double 变量的总和打印到小数点后一位。

3.与您作为输入读取的字符串连接并在新行上打印结果。 (完成这个程序)

 int main()
{

double d = 4.0;
string s = "hello and welcome ";

//write ur code here
// double variable
//string variable
//i/p double from user
// i/p string from user
// print sum of double
// print concatenated string

样本 i/p=--- 4.0乌芒马哈特!

样本o/p----8.0您好,欢迎 umang mahant!

 //this is my code but it isnt taking the line as input i really dont know why?
#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main() {
double d = 4.0;
string s = "hello and welcome ";
double b;
string s2;
cin>>b;
getline(cin, s2, '\n');
cout<<d+b<<"\n";
cout<<s<<s2<<"\n";
}

最佳答案

先把s改成

s = "hello and welcome"

然后看看下面的代码

#include <strtk.hpp>

double sum = d + b ; // adding doubles

std::string sum_as_string = strtk::type_to_string<double>(sum); //converted sum to string

std::string final_string = sum_as_string + s2 + s;//concatenate your input string to sum string and s string

现在打印 final_string。

(您实际上并没有连接字符串,将它们打印在一起不是解决方案!)在 getline(cin, s2) 之后插入这段代码并删除两个 cout 语句然后最后写入

 cout<<final_string<<"\n";

如果你不想实际连接字符串,那么你可以只修改输入函数 getline

您的 hackerrank 挑战的答案

int p;
double q;
string s2,result;

// Declare second integer, double, and String variables.

// Read and save an integer, double, and String to your variables.
cin>>p;
cin>>q;
getline(cin >> ws ,s2);

// Note: If you have trouble reading the entire string, please go back and review the Tutorial closely.

// Print the sum of both integer variables on a new line.
cout<<p+i<<"\n";


// Print the sum of the double variables on a new line.
std::cout << std::fixed;
std::cout << std::setprecision(1);
cout<<q+d<<"\n";
// Concatenate and print the String variables on a new line
result = s + s2;
cout<<result<<"\n";

关于c++ - 如何在将 double 作为输入后将整行作为字符串变量的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42136556/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com