2013-02-13 68 views
-1

你能,请帮助得到这个格式的输入:阅读阵列格式输入

{1,2,3,4} 

,并与整数转换为数组?

int * ns = new int [n]; 
    cin >> ns; 

这不起作用。我应该如何改变它?

+0

因为它的C++,答案的第一部分将是“使用'std :: vector'而不是'new int [n]'”。 – 2013-02-13 12:49:19

+0

不,用户键入输入 – Bek 2013-02-13 12:55:29

回答

0
using namespace std; 
typedef istream_iterator<int> It; 
vector<int> v; 
copy(It(cin), It(), back_inserter(v)); 
+0

它是如何工作的? – 2013-02-13 12:55:35

+0

您可以阅读我使用的功能的文档。它只是将所有可以从std :: cin的复制到矢量中。 – 2013-02-13 12:56:48

+0

它没有,与指定的输入:http://ideone.com/nvG1bE – Johnsyweb 2013-02-13 12:57:24

0

您需要逐个读取元素并将它们存储到数组中。

int aNoOfElements = 0; 
cin >> aNoOfElements; 
int *anArray = new int[ aNoOfElements];  //allocate memory to hold aNoOfElements 

for(int i = 0; i < aNoOfElements; i++) 
{ 
    cin >> anArray[ i ];     // Read each input 
} 
0

您需要解析输入。以字符串形式输入,然后检查符合您需要的格式。一种算法,您可以使用:

  1. 检查的第一个字符是“{”
  2. 如果是,则初始化变量(比如温度)来保存你即将获得的数量(作为字符串)与空字符串,否则错误
  3. 下一个读取字符
  4. ,如果它是“0”之间的“9”,然后将其追加到temp中,并返回到第3步,否则到步骤5
  5. 如果它是一个逗号或'}',然后将temp转换为整数并将其放入数组中,用空字符串重新初始化temp,否则错误
  6. 仍然在相同的字符,如果它是一个逗号,然后回到步骤3,否则做

我希望你可以把上面的算法形成工作代码,好运:)

PS:欢迎告诉我你是否发现了一个bug