2013-04-05 77 views
0

所以我如下得到的,我有来连接2个字符数组的锻炼 -在C++(狡猾)串联字符数组

棘手的部分是我不允许使用指针,字符串库或任何类型的动态数组。

怎么办?

编辑:我不需要打印它,我需要的变量具有值:东西/ input_text,因为我要用于别的东西!编辑2:我不能使用< string>库,这意味着我不能在该库上使用strcat()或其他任何东西。我提供了另一个模块,触发如下:

void thing(group, stuff, more_stuff); 

就是这样。

+1

打印一个那么其他的? – 2013-04-05 18:12:31

+0

你想在C或C++? C有'strcat'&'strncpy'等......要非常小心地使用。 C++给你'std :: string' – 2013-04-05 18:13:19

+0

返回或打印?有一个很大的区别 – KevinDTimm 2013-04-05 18:14:24

回答

3

像这样的东西?

#include <iostream> 

using namespace std; 
const int MAXI=100; 

int main() 
{ 
    char group[MAXI+7]="things/"; 
    char input[MAXI]; 
    cin >> input; 
    for(int i=0; i<MAXI; i++) 
    { 
     group[7+i]=input[i]; 
     if(input[i]=='\0') break;//if the string is shorter than MAXI 
    } 
    cout << group << endl; 
} 
+0

好的,是的,我完全没用,这很容易,但我一定会找到一个隐藏的方式来做到这一点。谢谢soooo太多:) – Zasito 2013-04-05 18:22:39

+0

你的代码,可能会离开'group'没有一个NULL终止符,这将是*糟糕*。您还应该使用非常明亮的标记突出显示'cin >> input'语句中缓冲区溢出的危险,以帮助OP学习如何及早发现潜在问题。 – 2013-04-05 18:25:59

1
#include <iostream> 

using namespace std; 

int main(int argc, char **argv) 
{ 
    const int MAXI=100; 
    char group[MAXI+7]="things/"; 
    char input[MAXI]; 

    // Warning: this could potentially overflow the buffer 
    // if the user types a string longer than MAXI - 1 
    // characters 
    cin >> input; 

    // Be careful - group only contains MAXI plus 7 characters 
    // and 7 of those are already taken. Which means we can only 
    // write up to MAXI-1 characters, including the NULL terminator. 
    for(int i = 0; (i < MAXI - 1) && (input[i] != 0); i++) 
    { 
     group[i + 7] = input[i]; 
     group[i + 8] = 0; // ensure null termination, always 
    } 

    cout << group << endl; 

    return 0; 
} 
+0

如果您倾向于使用'i'超出范围,您可以避免重复'group [i + 8] = 0'。这是OP的一个练习。 – 2013-04-05 18:28:15

+0

我爱你们俩<(^.^)> – Zasito 2013-04-05 18:42:15