我似乎无法获得阵列的长度或向后打印!请帮忙?!
void GetStringLenght和Print Backwards底部的函数不起作用
#include <iostream>
void ReadString(char* c, int maxLength);
void GetStringLength(char* c, int* length);
void PrintString(char* const c);
void PrintStringBackwards(char* const c);
int main()
{
const int SIZE = 50;
char ca[SIZE];
char* pc = ca;
int fPrints = 0;
int bPrints = 0;
int lengthChecks = 0;
char selection = 'z';
while (selection != 'Q') {
std::cout << "\n[ 1] Test ReadString\n";
std::cout << "[ 2] Test GetStringLength\n";
std::cout << "[ 3] Test PrintString\n";
std::cout << "[ 4] Test PrintStringBackwards\n";
std::cout << "[Q] Quit\n";
std::cout << "Selection: ";
std::cin >> selection;
std::cin.ignore();
std::cout << std::endl;
switch (selection) {
//Test ReadString
case '1':
ReadString(pc, SIZE);
break;
//Test GetStringLength
case '2': {
lengthChecks += 1;
int length = 0;
GetStringLength(pc, &length);
std::cout << "Length[" << lengthChecks << "]=" << length << std::endl;
break;
}
//Test PrintString
case '3':
fPrints += 1;
std::cout << "Foward[" << fPrints << "]=";
PrintString(pc);
std::cout << std::endl;
break;
//[ 4] Test PrintStringBackwards
case '4':
bPrints += 1;
std::cout << "Backwards[" << bPrints << "]=";
PrintStringBackwards(pc);
std::cout << std::endl;
break;
case 'Q':
break;
default:
break;
} //end switch
} //end while
std::cout << "Press ENTER";
std::cin.get();
return 0;
}
void ReadString(char* c, int maxLength)
{
std::cout << "Enter a string less than " << maxLength << " characters." << std::endl;
std::cin.getline(c, maxLength, '\n');
}
//BELOW THIS DOESNT WORK EITHER///
//////////////////////////////////////////
void GetStringLength(char* c, int* length)
{
for (int i = 0; i < *length; i++) {
if (c[i] == '\0')
*length = i - 1;
}
}
void PrintString(char* const c)
{
int counter = 0;
for (int i = 0; i < 100; i++) {
if (c[i] == '\0') {
counter = i;
break;
} //end if
} //end for
for (int j = 0; j < counter; j++) {
std::cout << c[j];
if (j == counter)
std::cout << '\0';
} //end for
std::cout << std::endl;
} //end void
void PrintStringBackwards(char* const c)
{
//this is where I’m lost! I’ve tried 25 different ways and everything is error.
}
答案 0 :(得分:0)
要获得C字符串(char*
)的长度,您可以使用strlen(...)
。
要向后打印,请执行以下操作:
for(int i = strlen(str) - 1; i >= 0; --i)
std::cout << str[i];
答案 1 :(得分:0)
考虑for (int i = 0; i < *length; i++)
,其中i
和*length
都是0
,就像你的情况一样......那个循环会执行吗?不...考虑一个循环,当x
为0
时,return x;
设置为str[x]
和'\0'
。即strlen
中的循环就是这样做的。
对于向后打印,从最高索引开始(由strlen
或您的函数返回一次)并递减直到达到0
,然后在这些偏移处打印字符。
strlen
中提供了{p> <cstring>
,而不仅仅是<string>
...因为它是强制函数,所以它始终是任何C ++实现的一部分。您应该只使用strlen
...