从文件中读取两个向量

时间:2015-05-08 09:37:14

标签: c++ file

Problem is described here. 我尝试使用下面的代码解决它,但它无法正常工作。

const char* filename = "test.txt";
ifstream file1(filename);
vector<int> v1;
vector<int> v2;
vector<int> res;

int number;
char c;

while(1){
    while(1){
        v1.push_back(number);
        file1.get(c);
        if (c==';') break;
    }

    while(1){
        v2.push_back(number);
        file1.get(c);
        if (c=='\n') break;
    }

    for (vector<int>::iterator it = v2.begin(); it!=v2.end(); it++)
        cout << *it << ',';
    cout << endl;
    file1.get(c);
    if (c==EOF) break;
    file1.unget();
}

读取行尾有问题。 c=='\n'是对的吗?

1 个答案:

答案 0 :(得分:2)

To read a line, you should use:

#include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "common.h" #include <sys/shm.h> int memoryID; struct wrapper *memory; int check_prime(int a); int main(int argc, char **argv) { srand(time(NULL)); key_t sharedMemoryKey = ftok(".",MEMORY_KEY); if(sharedMemoryKey==-1) { perror("ftok():"); exit(1); } memoryID=shmget(sharedMemoryKey,sizeof(struct wrapper),0); if(memoryID==-1) { perror("shmget(): "); exit(1); } memory = shmat(memoryID,NULL,0); if(memory== (void*)-1) { perror("shmat():"); exit(1); } while(1) { sem_wait(&memory->full); sem_wait(&memory->cmutex); int n = memory->n; int temp = (memory->array)[n]; printf("Removed item: %d\tPrime:%d\tNumer of tasks left:%d\n", temp, check_prime(temp),n); memory->n--; usleep(10000); sem_post(&memory->cmutex); sem_post(&memory->empty); } }

In your case, with a delimiter of #define MEMORY_KEY 12 #define SIZE_OF_ARRAY 10 struct wrapper { int array[SIZE_OF_ARRAY]; sem_t empty; sem_t pmutex; sem_t cmutex; sem_t full; int n; };

Then you can parse numbers in the same way, by using delimiter of istream& getline (istream& is, string& str, char delim);

like this:

';'