我在C++中包含头文件时遇到问题.据我所知,放入using namespace std标题并不是一个好的设计,但是当我尝试删除它时出现了一些错误.这是头文件中的代码:
#include <iostream>
#include <string>
//using namespace std;
class Messages
{
public:
Messages(string sender, string recipient,int time);
void append();
string to_string();
private:
int time;
string sender;
string recipient;
string text;
};
Run Code Online (Sandbox Code Playgroud)
我确实包含了<string>.但是,如果我不使用namespace std,那么我的所有字符串都会显示错误.我不想添加using namespace std头文件,因为它是一个糟糕的设计.那么我该如何解决呢?
提前致谢.
我试图在C++中反转char数组.这是我的代码:
void reverse(char s[]);
int main()
{
char s [] = "Harry";
cout << reverse(s) << endl;
system("PAUSE");
return 0;
}
void reverse(char s[])
{
if( strlen( s ) > 0 ) {
char* first = &s[ 0 ];
char* last = &s[ strlen( s ) - 1 ];
while( first < last ) {
char tmp = *first;
*first = *last;
*last = tmp;
++first;
--last;
}
return;
}
Run Code Online (Sandbox Code Playgroud)
但是,我在cout << reverse(s)<< endl; 位于main方法中的那行,我不知道为什么.错误消息是没有操作符匹配这些操作数.有人可以帮我解决这个问题吗?
提前致谢.
这是我的问题:
编写一个反转字符串的函数void reverse(char s []).例如,"Harry"变成"yrraH".
这是我的代码:
void reverse(char s[]);
int main()
{
char s [] = "Harry";
reverse(s);
cout << s << endl;
system("PAUSE");
return 0;
}
void reverse(char s[])
{
int length = strlen(s);
int c, i ,j;
for(int i=0, j=length-1 ; i<j ; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
Run Code Online (Sandbox Code Playgroud)
它可以完美地扭转字符串.但是,我被要求用指针做.所以根据我的想法,首先我指定ap指针来获取字符串中的第一个char.然后我分配一个指针来获取字符串的最后一个字符串.I循环通过反转阵列.但是当我试图这样做以获得最后一个字符时:
char *q = strlen(s-1);
Run Code Online (Sandbox Code Playgroud)
我收到了一个错误.有人可以帮我用指针解决这个问题吗?
更新部分
if (strlen(s) > 0(
{
char* first = &s[0];
char*last = &s[strlen(s)-1];
while(first < …Run Code Online (Sandbox Code Playgroud) 我对指针有疑问.这是我的问题:
编写一个函数
int* read_data(int& size),cin通过输入Q 来读取数据,直到用户终止输入.该函数应将size参数设置为数字输入的数量.返回指向堆上数组的指针.该数组应具有完全大小的元素.当然,您不会在一开始就知道用户将输入多少元素.从10个元素的数组开始,每当数组填满时,大小加倍.最后,分配一个正确大小的数组并将所有输入复制到其中.一定要删除任何中间数组.
这是我的代码:
int* read_data(int& size);
int main()
{
int size ;
int* account_pointer = read_data(size);
int* account_array = new int[size];
int* bigger_array = new int[2 * size];
for (int i = 0; i < size; i++)
{
bigger_array[i] = account_array[i];
}
delete[] account_array;
account_array = bigger_array;
size = 2 * size;
system("PAUSE");
return 0;
}
int* read_data(int& size)
{
int input;
cout << "Enter integer, Q to quit : " ;
while(cin …Run Code Online (Sandbox Code Playgroud)