本來一個很簡單的字符串拼接問題,因為題目要在2個字符串之間加逗號和空格,感覺很煩了,
我的方法代碼看起來很丑,有沒有更好方法,謝謝!
#include<iostream>
#include<string>
int main()
{
using namespace std;
string s1,s2,s3;
char t[3]={',','\0'};
cout << "Enter your first name: ";
cin >> s1;
cout << "Enter yor last name: ";
cin >> s2;
s3=s1+t;
cout << "Here's the information in a single string: " << s3 << ' ' << s2 <<endl;
return 0;
}
#include<iostream>
#include<cstring>
int main()
{
using namespace std;
const int n=20;
char first[n],last[n];
cout << "Enter your first name: ";
cin.getline(first,n);
cout << "Enter your last name: ";
cin.getline(last,n);
char t[2]={',','\0'};
cout << "Here's the information in a single string: " << strcat(first,t) << ' ' << last <<endl;
return 0;
}
你用的方法沒什麼問題吧,再簡單可能就是用一個string放空格和逗號,然後兩個string類型的變量再相加了