在将double作为输入后如何将整行作为输入到字符串变量?

时间:2017-02-09 12:19:26

标签: c++ string

目标:用c ++编写程序

1.Declare变量:double类型之一,String类型之一。

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

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 umang mahant!

样本o / p ---- 8 你好,欢迎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";
   }

2 个答案:

答案 0 :(得分:1)

首先将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

回答您的黑客挑战

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";

答案 1 :(得分:0)

我假设您在样本输入和输出下方发布的代码是您要询问的代码。

问题在于你的getline()函数。你为什么在这个函数中有3个参数?它会产生错误。您应该将getline()语句更改为:

    getline(cin, s2);

这消除了错误,您的代码可以正常工作。