suxue / cplusplus-practices-2011

Automatically exported from code.google.com/p/cplusplus-practices-2011
0 stars 0 forks source link

可不可以随便输入一组字符,用new动态分配存储空间(不计算输入字符个数),然后存入一数组。好像挺矛盾啊,new之前要知道数组长度,new之后才能输入字符 #9

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
What steps will reproduce the problem?
1.
2.
3.

What is the expected output? What do you see instead?

Please use labels and text to provide additional information.

Original issue reported on code.google.com by kkerF...@gmail.com on 21 Sep 2011 at 2:19

GoogleCodeExporter commented 8 years ago
你的意思是读入之前不知道输入字符的个数,然后动态读入��
�

Original comment by Cdegre...@gmail.com on 21 Sep 2011 at 2:22

GoogleCodeExporter commented 8 years ago
对啊,若随便输入一堆,知道有点不现实

Original comment by kkerF...@gmail.com on 21 Sep 2011 at 2:31

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago
实际上是可以实现的,
每读入一个字符,就再动态申请一个字符,用链表来储存就��
�了

具体如下:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <queue>
#include <vector>
#include <stack>
#include <map>
#include <string>
using namespace std;
struct CH
{
    char ch;
    int pos;
    CH* next;
    CH()
    {
        next=NULL;
    }
}*P,*Q;
int main(int argc, char *argv[])
{
    char ch;
    char *p;
    int T=0;
    CH head;
    P=new CH;
    head.next=P;
    head.pos=T++;
    scanf("%c",&ch);
    P->ch=ch;
    P->pos=T++;
    while(scanf("%c",&ch),ch!='\n')
    {
        Q=new CH;
        Q->ch=ch;
        Q->pos=T++;
        P->next=Q;
        P=Q;
    }
    P=head.next;
    while(P->next!=NULL)
    {
        printf("%c",P->ch);
        P=P->next;
    }
    if(P!=NULL)printf("%c",P->ch);
    while(P->next!=NULL)
    {
        Q=P->next;
        delete P->next;
        P->next=Q->next;
    }
    delete P,Q;
    printf("\n");
    return 0;
}

Original comment by Cdegre...@gmail.com on 21 Sep 2011 at 4:18